So we're working on converting some projects at work from Ninject to Autofac, and we've stumbled on something really neat within Ninject that we can't figure out how to do in Autofac. In our application, we have an interface called ISession
which is implemented in two different concrete types. One goes to an Oracle database, and the other goes to an MS-SQL database.
We have controllers in our MVC application that need only one concrete implementation of ISession based on which controller they are being injected into. For example:
Bind<IFoo>().To<Foo1>(); Bind<IFoo>().To<Foo2>().WhenInjectedInto<OracleController>();
My question is: how do we achieve the same result in Autofac? When IFoo
is injected into any controller, Foo1
should be provided by default, however in one special case, we need Foo2
instead.
Thanks for any help in advance!
Autofac allows you to specify how many instances of a component can exist and how they will be shared between other components. Controlling the scope of a component independently of its definition is a very important improvement over traditional methods like defining singletons through a static Instance property.
Autofac is a . Net-based IoC container. When classes interact with one another, it manages the dependencies between them that allow applications to remain flexible as they grow in size and complexity. Autofac is the most widely used DI/IoC container for ASP.NET, and it is fully compatible with.NET Core as well.
With Autofac you can achieve this by doing the registration the other way around. So you should declare that you want to use the "speciel" service when you register the OracleController not when you register the IFoo.
containerBuilder.RegisterType<Foo1>().As<IFoo>(); containerBuilder.RegisterType<Foo2>().Named<IFoo>("oracle"); containerBuilder.RegisterType<OracleController>().WithParameter(ResolvedParameter.ForNamed<IFoo>("oracle"));
The Named registration "oracle" ensures that the default IFoo instance will be Foo1 and you only get Foo2 when you explicitly request it by name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With