开发者

Autofac equivalent of Ninject's WhenInjectedInto()

开发者 https://www.devze.com 2023-04-10 17:21 出处:网络
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 applica

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:

开发者_StackOverflow社区
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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号