[英]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.