How can I nest two or more dependencies with the same interface?

Consider the following code

public interface ISomeInterface { void DoSomething(); } public class A : ISomeInterface { public void DoSomething() { } } public class B : ISomeInterface { public void DoSomething() { } } 

And then one class using 2 interfaces:

 public class C : IC { protected ISomeInterface _dependency1; protected ISomeInterface _dependency2; public C ( ISomeInterface dependency1, ISomeInterface dependency2 ) { _dependency1 = dependency1; _dependency2 = dependency2; } } 

I would like to add A in dependency 1 and B in dependency2. I know I can do something like this:

 builder.RegisterType<C>().As<IC>() .WithParameter( "dependency1", new A() ) .WithParameter( "dependency2", new B() ); 

But I know that there is a better way to do this with Autofac.

+4
source share
2 answers

When you register your ISomeInterface implantation, you can give them a name :

 containerBuilder.RegisterType<A>().Named<ISomeInterface>("A"); containerBuilder.RegisterType<B>().Named<ISomeInterface>("B"); 

You can then register your C to resolve its arguments using specific names:

 containerBuilder.Register(c => new C(c.ResolveNamed<ISomeInterface>("A"), c.ResolveNamed<ISomeInterface>("B"))) .As<IC>(); 

Using the code above, you must specify all the parameters of the C constructor, even if some parameters do not need "named" registrations.

So, if you only want to specify "named" parameters, you can use WithParameter together permission:

 containerBuilder.RegisterType<C>().As<IC>() .WithParameter((p, c) => p.Name == "dependency1", (p, c) => c.ResolveNamed<ISomeInterface>("A")) .WithParameter((p, c) => p.Name == "dependency2", (p, c) => c.ResolveNamed<ISomeInterface>("B")); 
+2
source

First of all, why do you need to introduce two instances of the same interface? Should it be something that sets them apart?

My suggestion is that you register two sub-interfaces, i.e. ISomeInterface1: ISomeInterface ISomeInterface2: ISomeInterface and enter these two. Then you do not have to deal with the specified parameters.

+1
source

Source: https://habr.com/ru/post/1442338/


All Articles