【问题标题】:Injection in web api controller not using Single InstanceWeb api控制器中的注入不使用单实例
【发布时间】:2019-11-09 17:33:00
【问题描述】:

我有一个在我的容器中注册为单个实例的服务

public class MyModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<MyService>()
            .As<IMyService>()
            .SingleInstance();

    }
}

容器如下创建

 public static IContainer SetupContainer()
 {
     var builder = new ContainerBuilder();
     var moduleTypes = TypeCache.GetTypes(x => x.IsClassEx() && !x.IsAbstractEx() && x.ImplementsInterfaceEx<IModule>());

     foreach (var moduleType in moduleTypes)
     {
        if (Activator.CreateInstance(moduleType) is IModule module)
           builder.RegisterModule(module);
     }

     var assemblies = AppDomain.CurrentDomain.GetAssemblies();
     builder.RegisterAssemblyModules(assemblies);

     var result = builder.Build();
     return result;
  }

这一切都在正常代码中完美运行 - 我可以注入我的服务并按预期解决

但是,当我尝试将我的服务注入 Web api 控制器时,该服务再次被解析,但 Autofac 为我提供了一个新的服务实例

如何防止这种行为,以便注入最初创建的实例?

【问题讨论】:

  • 您能分享一下您是如何将 Autofac 集成到 ASP.net Web API 的吗?

标签: c# autofac autofac-configuration autofac-module


【解决方案1】:

我认为您在这里缺少的是您实际上并没有在正确的位置解析您的容器,因此根据您使用的集成类型,您可以执行以下操作之一。

//For OWIN you could do something like the following.
public class Startup
{
  public void Configuration(IAppBuilder app)
  {
    var container = YourObject.SetupContainer();

    // Register the Autofac middleware FIRST. This also adds
    // Autofac-injected middleware registered with the container.
    app.UseAutofacMiddleware(container);

    // ...then register your other middleware not registered
    // with Autofac.
  }
}

//In your Global.asax.cs 

    protected void Application_Start() 
    {

       var container = YourObject.SetupContainer();
       DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

    }

MVC Example OWIN Implementation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多