我的 web api 自托管应用程序中有一个属性,我想将其注入(inject)我的 Controller ,该 Controller 使用我的自定义 IoC 框架通过反射加载,这是我的启动代码:
public CustomClass StuffInstance { get; set; }
// This method is required by Katana:
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
var webApiConfiguration = ConfigureWebApi();
// Use the extension method provided by the WebApi.Owin library:
app.UseWebApi(webApiConfiguration);
}
我的 Controller 大多是脚手架,有些是这样的:
// PUT: api/EventTypeDescriptions/5
[ResponseType(typeof(void))]
public IHttpActionResult PutStuff(int id, int something)
{
//do stuff
//here i would like to use StuffInstance like a singleton
return StatusCode(HttpStatusCode.NoContent);
}
如何将 StuffInstance 注入(inject)我的 Controller ?此信息将与任何制作 IoC 框架的人相关
最佳答案
我在这个链接中找到了将实例注入(inject)我的 Controller 的信息:
http://www.asp.net/web-api/overview/advanced/dependency-injection
基本上我为我的自定义 IoC 库实现了一个依赖解析器
如果有人有同样的问题,这里是代码,也许对于其他 IoC 框架它需要更多的工作
public class CustomIocDependencyResolver : IDependencyResolver
{
private readonly CustomIoc container;
public ComponentLoaderWebApiDependencyResolver(CustomIoc container)
{
this.container = container;
}
IDependencyScope IDependencyResolver.BeginScope()
{
return new CustomIocDependencyResolver(container);
}
Object IDependencyScope.GetService(Type serviceType)
{
return container.GetInstance(serviceType);
}
IEnumerable<Object> IDependencyScope.GetServices(Type serviceType)
{
return container.GetAllInstances(serviceType);
}
public void Dispose()
{
}
}
现在我的武士刀配置如下:
// This method is required by Katana:
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
var config = ConfigureWebApi();
config.DependencyResolver = CustomIocDependencyResolver(container);
// Use the extension method provided by the WebApi.Owin library:
app.UseWebApi(config);
}
作为我的自定义 IoC 实例的容器
关于c# - Web API 自托管自定义 ioc 将数据注入(inject) Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32915491/