2

I want to inject specific type when some conditions are met. For example, i have got an interface like below.

public interface IMyInterface{

}

And also two classes that implement this interface

public class MyClassA : IMyInterface {
}

and

public class MyClassB : IMyInterface {
}

Finally i have some service class that gets a constructor parameter as IMyInterface.

public class ServiceA{
private IMyInterface _interfaceClass;
public ServiceA(IMyInterface interfaceClass){
_interfaceClass = interfaceClass
}
}

and

public class ServiceB{
private IMyInterface _interfaceClass;
public ServiceA(IMyInterface interfaceClass){
_interfaceClass = interfaceClass
}
}

Now because of some architectural constraints ServiceA must get MyClassA as constructor parameter and ServiceB must get MyClassB as constructor parameter.

Normally i am using Autofac like below

var builder = new ContainerBuilder();
builder.RegisterType<MyClassA>().As<IMyInterface>().InstancePerApiRequest();

But i couldn't find the way how can i force Autofac to select right type for specific type. I looked to Named<> feature but couldn't solve problem.

bahadir arslan
  • 4,535
  • 7
  • 44
  • 82
  • possible duplicate of [Injecting a specific instance of an interface using Autofac](http://stackoverflow.com/questions/4989676/injecting-a-specific-instance-of-an-interface-using-autofac) – Travis Illig May 23 '13 at 17:06

1 Answers1

2

It sounds like you have violated Liskov substitution principle

Now because of some architectural constraints ServiceA must get MyClassA as constructor parameter and ServiceB must get MyClassB as constructor parameter.

I'm not sure that Autofac supports context based injection - why don't you just make each Service dependent on the implementation it requires?

public class ServiceA
{
    private IMyInterface _interfaceClass;
    public ServiceA(MyClassA interfaceClass)
    {
        _interfaceClass = interfaceClass
    }
}
qujck
  • 14,388
  • 4
  • 45
  • 74
  • Actually you might be right, i didn't try using class type as parameter type. Thanks for answer – bahadir arslan May 23 '13 at 16:50
  • 1
    "make each Service dependent on the implementation it requires". That would unfortunately lead to a violation of the Interface Segregation Principle. The problem here is that there is ambiguity in the design. It's better to hide `MyClassA` and `MyClassB` each behind a different abstraction to prevent the ambiguity altogether. – Steven Jun 04 '13 at 07:40
  • 1
    Autofac supports context based injection: https://stackoverflow.com/questions/30835744/how-to-use-autofac-to-inject-specific-implementation-in-constructor?rq=1 – Olivier de Rivoyre Jun 04 '18 at 14:42