I have the following controller:
public class MyController : Controller {
private readonly IService service;
private readonly int intDependency;
public MyController(IService service, int intDependency) {
this.service = service;
this.intDependency = intDependency;
}
...
}
Obviously resolution does not work, nor can I provide constructor parameter using a delegate, since this would end up with multiple constructor registration.
What is the correct way to proceed in this case? Is it generally uncorrect injecting value type as a dependency? Would it be a better practice to wrap the dependency behind an interface?
Is it generally uncorrect injecting value type as a dependency?
Indeed, as you can see there is no way for the injector to know which int
it has to inject. Doesn't really make sense.
Would it be a better practice to wrap the dependency behind an interface?
Yes.
What is the correct way to proceed in this case?
You said it. Either an interface or a class.
Example:
public class MyConfig
{
public int MyInt {get; set;}
}
And you could configure SimpleInjector like this:
container.RegisterSingleton(new MyConfig { MyInt = 42 });
and your controller would be:
public MyController(IService service, MyConfig config) { ...
Note: There is a way to inject primitive types : Primitive Dependencies with Simple Injector However, it's way easier and cleaner to just wrap the primitive in a class like my example.
Would it be a better practice to wrap the dependency behind an interface?
Yes, that would be the suggested solution. Value types aren't supported. Do instead of injecting the value directly, wrap it in a class and inject that.
Best practice to put an interface over the implementation but this is not necessary perse. Simple Injector doesn't matter. So this will work:
public class Values
{
public Values(int value)
{
this.SomeValue = value;
}
public int SomeValue { get; }
}
// Register as
container.RegisterSingleton<Values>(() => new Values(1));
There are options, although a bit ugly and IMO not the way to go. These are described here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.