c# - Web API 自托管自定义 ioc 将数据注入(inject) Controller

标签 c# asp.net-web-api inversion-of-control ioc-container self-hosting

我的 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/

相关文章:

c# - 创建目录 - 访问被拒绝

c# - 在 C# 字符串中丢弃空格后的字符

asp.net-web-api - Asp.net Web Api 的基本项目模板?

entity-framework - 使用多个参数注册 DbContext

Java——反射。动态创建的setter方法中的Set Value多参数类对象

c# - ConcurrentDictionary AddOrUpdate 按谓词

C# System.Net 跟踪日志 - 只跟踪一种方法而忽略其他方法?

c# - 调试器正在寻找 executioncontext.cs,如何修复?

dependency-injection - Autofac 未解决模型绑定(bind)器依赖项

java - 将 AppContext 实现为 Play 插件