[英]How to do constructor injection in Simple Injector if constructor takes another interface?
I am trying to instantiate HomedataAccess
class which takes string and an interface IQueryManager
as constructor argument. 我试图实例化HomedataAccess
类,该类将字符串和接口IQueryManager
作为构造函数参数。 How do I register it? 我该如何注册?
Till now I have done following and it works but I don't like this way: 到现在为止,我已经完成了以下工作,并且可以正常工作,但是我不喜欢这种方式:
Kernel.Register(() => new HomeDataAccess("anandv4",
new SqlServerQueryManager(new SqlServerConnectionManager())));
Is there another way of doing this? 还有另一种方法吗?
What you're doing can work just fine. 您正在做的事情可以正常工作。 There's nothing wrong with that. 没有错。 Especially when your SqlServerQueryManager
and SqlServerConnectionManager
are only used within your HomeDataAccess
class`. 特别是当SqlServerQueryManager
和SqlServerConnectionManager
仅在HomeDataAccess
类中使用时。
In case however, the IQueryManager
abstraction is used in multiple places, it becomes more problematic, because it would cause the registration to become duplicated and this could increase maintenance. 但是,如果在多个地方使用IQueryManager
抽象,则会变得更加成问题,因为这将导致注册重复,并且这可能会增加维护。
A solution might be to do the following: 一个解决方案可能是执行以下操作:
Kernel.Register(() => new HomeDataAccess(
"anandv4",
Kernel.GetInstance<IQueryManager>());
The downside of this however is that this completely blinds Simple Injector when it runs its diagnostics. 但是,这样做的缺点是,在运行诊断程序时,这会使Simple Injector完全蒙蔽。 So this is not advised. 因此,不建议这样做。
There are ways to extend Simple Injector to so that primitive dependencies like these can be registered, but it's usually a much easier solution to wrap the primitive value into a DTO. 有多种方法可以将 Simple Injector 扩展为,以便可以注册类似这些原始类型的依赖关系,但是通常,将原始值包装到DTO中的方法要容易得多。 For instance: 例如:
public class HomeDataAccessConfig
{
public readonly string UserName;
public HomeDataAccessConfig (string userNamr) {
if (string.IsNullOrWhiteSpace(userName)) throw new ...
this.Usrrname = userName.
}
}
public class HomeDataAccess
{
private readonly HomeDataAccessConfig config;
private readonly IQueryManager manager;
public HomeDataAccess(HomeDataAccessConfig config, IQueryManager manager) {
this.config = config;
this.manager = manager;
}
}
This allows you to do the registration as follows: 这使您可以按以下方式进行注册:
Kernel.RegisterSingleton(new HomeDataAccessConfig("anandv4"));
Kernel.Register<HomeDataAccess>();
Kernel.Register<IQueryManager>(() =>
new SqlServerQueryManager(new SqlServerConnectionManager()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.