23

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!

Scott Arrington
  • 12,325
  • 3
  • 42
  • 54

1 Answers1

26

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.

nemesv
  • 138,284
  • 16
  • 416
  • 359
  • 2
    As you mentioned, this is not full equivalent. This works only if you have posibility to change OracleController registration. But Ninject's WhenInjectedInto can override parameters binding without modifying original registration. So what should I do if I really need this case? – Igor S Oct 10 '17 at 19:19