[英]How can I create instance Dynamically with parameter constructor resolve using autofac DI
我的代码看起来像这样
private void installData()
{
var dataInstallServices = new List<IDataInstallationService>();
var dataInstallServiceTypes=_typeFinder.FindClassesOfType<IDataInstallationService>();
foreach (var dataInstallServiceType in dataInstallServiceTypes)
dataInstallServices.Add((IDataInstallationService)Activator.CreateInstance(dataInstallServiceType));
foreach (var installServie in dataInstallServices)
installServie.InstallData();
}
我的问题是
dataInstallServices.Add((IDataInstallationService)Activator.CreateInstance(dataInstallServiceType,"parameters resolve using autofac"))
我注册了所有依赖关系,但没有为此对象定义无参数构造函数。 例外
如果您使用的是AutoFac,则无需使用Activator创建实例。
说出上面您想做的事情,住在一个名为DataService
的类中,该类具有以下依赖关系:
public class DataInstallerA : IDataInstaller {
public DataInstallerA(SubDependencyA a){}
}
public class DataInstallerB : IDataInstaller {
public DataInstallerA(SubDependencyB b){}
}
使用以下AutoFac注册:
builder.RegisterType<SubDependencyA>();
builder.RegisterType<SubDependencyB>();
builder.RegisterType<DataInstallerA>().As<IDataInstaller>();
builder.RegisterType<DataInstallerA>().As<IDataInstaller>();
builder.RegisterType<DataService>();
然后,您的DataService可能如下所示:
public class DataService
{
private IEnumerable<IDataInstaller> _dataInstallers;
public DataService(IEnumerable<IDataInstaller> dataInstallers) {
_dataInstallers = dataInstallers;
}
public void Install() {
foreach (var installer in _dataInstallers)
installer.InstallData();
}
}
DataService
不需要知道如何创建所有IDataInstaller
实例,AutoFac可以做到这一点,它只需要它们的集合即可。
请注意,即使您实际上没有注册IEnumerable<IDataInstaller>
当您注册类型时,AutoFac IEnumerable<IDataInstaller>
隐式提供一些额外的注册。 请参阅http://autofac.readthedocs.org/en/latest/resolve/relationships.html 。
在使用Activator.CreateInstance(Type t)
方法时,应确保该类型具有可传递给其参数的类型的无参数构造函数,否则它将抛出一个异常。
为什么没有默认构造函数?
在类中使用参数指定构造函数时,编译器将删除默认构造函数。
using System;
public class Program
{
public static void Main()
{
Test t = new Test() //will give you compile time error.
Test t1 = new Test(""); //should work fine.
}
}
public class Test
{
public Test(string a)
{
}
}
使用另一种重载方法在此处传递构造函数参数,如下所示:
Activator.CreateInstance(typeof(T), param1, param2);
该方法的MSDN文档在这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.