Autofac Lifetimes and the Default Provider within a Matching Lifetime Scope

后端 未结 2 1826
失恋的感觉
失恋的感觉 2021-02-09 15:38

I have an ASP.NET MVC web application using Autofac for dependency injection. Occasionally, this web application will start a thread to do some work separate from the request t

相关标签:
2条回答
  • 2021-02-09 15:55

    Register the web Foo as normal, but don't register the other Foo. When creating the lifetime scope for the async task, use the overload of BeginLifetimeScope() that takes an action on ContainerBuilder. Register the background Foo in this action (b => b.Register()) and this should override the web one. (Small keyboard here sorry :))

    0 讨论(0)
  • 2021-02-09 16:00

    This can also be solved by using a tagged life time scope. Register your fisrt Foo as instance of your tagged scope:

    builder.RegisterType<Foo>().As<IFoo>.InstancePerMatchingLifetimeScope("YourScopeTag");
    

    And create the scope with the same tag you registered your dependencie:

      using (var Scope = Runtime.Container.BeginLifetimeScope("YourScopeTag"))
            {
                var Input = Scope.Resolve<T>();
                action(Input);
            }
    

    Haven't tested it, but it should work

    http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-matching-lifetime-scope

    0 讨论(0)
提交回复
热议问题