Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac equivalent of Ninject's WhenInjectedInto()

Tags:

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!

like image 259
Scott Anderson Avatar asked Oct 05 '11 17:10

Scott Anderson


People also ask

What is autofac for?

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.

What is autofac in. net Core?

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.


1 Answers

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.

like image 67
nemesv Avatar answered Sep 28 '22 13:09

nemesv