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.

1

1 Answer 1

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
    }
}
3
  • Actually you might be right, i didn't try using class type as parameter type. Thanks for answer Commented May 23, 2013 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
    Commented Jun 4, 2013 at 7:40
  • 1
    Autofac supports context based injection: stackoverflow.com/questions/30835744/… Commented Jun 4, 2018 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.