Reputation: 1211
I have recently began experimenting with dependency injection and IoC.
Here is an issue that bothers me... I have a dependency resolver, that basically allows me to do the following
injection.Register<IMyInterface, MySpecificType>();
This will automatically resolve the type, whenever something in the code asks for it and provide MySpecificType
as an implementation for IMyInterface
.
This works great for Controllers in ASP.NET for example, where the controller constructor has no parameters and is also dynamically invoked by the framework.
But what happens if I have my own custom class (in this case MySpecificType
), and I want to dynamically resolve it. That is, whenever something in my code requires IMyInterface
, the resolver should pass in MySpecificType
.
Here is an example :
injection.Register<IMyInterface, MySpecificType>();
public SomeClass(IMyInterface dependency)
{
//do something
}
Then somewhere in my code I wish to create a new instance ofSomeClass
.
var instance = new SomeClass(//What do i pass here)
What should I pass in the constructor. Ofcourse I could do something like new MySpecificType()
, but this would make my automatic dependency resolver pointless. Should I have a separate empty constuctor and use that or is this something that cannot happen.
Upvotes: 0
Views: 347
Reputation:
You should ask your IoC container to instantiate your class for you. Then it really depends on your IoC container.
For example, with autofac
var builder = new ContainerBuilder();
builder.RegisterType<MyComponent>().As<IService>();
var container = builder.Build();
using(var scope = container.BeginLifetimeScope())
{
var service = scope.Resolve<IService>();
}
Upvotes: 1