Im在autofac和im有一些問題綁定到特定的構造函數。AutoFac NamedParameter沒有正確解析
我有以下代碼:
var builder = new ContainerBuilder();
builder
.RegisterType<GenericIocFactory>()
.As<IGenericIocFactory>();
builder
.RegisterType<Product>()
.As<IProduct>()
.PropertiesAutowired();
IContainer Container = builder.Build();
IGenericIocFactory Fac = Container.Resolve<IGenericIocFactory>();
_product = Fac.Get<IProduct>(new Dictionary<string,object>() { {"returnEmpty" , false} }) as Product;
然後在工廠:
public interface IGenericIocFactory
{
T Get<T>(Dictionary<string,object> options) where T: class;
}
public class GenericIocFactory : IGenericIocFactory
{
private readonly IComponentContext _icoContext;
private object _options;
public GenericIocFactory(IComponentContext icoContext,bool isInjected = true)
{
_icoContext= icoContext;
}
public T Get<T>(Dictionary<string,object> options) where T: class
{
var _parameters = new List<Parameter>();
foreach (var parameter in options)
{
_parameters.Add(new NamedParameter(parameter.Key, parameter.Value));
}
return _icoContext.Resolve<T>(_parameters);
//operate on new object
// tried this as well
//return _icoContext.Resolve<T>(
//new NamedParameter("returnEmpty" , false)
//new TypedParameter(typeof(bool),false)
//);
}
}
這解決了一個產品,但不與構造我的期望。
目標構造
public Product(bool returnEmpty)
解決構造
public Product(IList<string> productCodes, string fields = "", string orderBy = "ProductCode")
有總共23個構造函數和一個解決還不是最大的(所以我不認爲它是貪婪)
即
public Product(string strFields, string strFrom, string strFilter, string strOrderBy, string whseCode,
bool addExistsInWharehouse, string additionalAfterorderBy, bool forceUniqueRecords = false)
也不是定義中的第一個也不是最後一個。
Im難怪任何人都可以看到我做錯了什麼。
爲什麼你需要DI對象似乎是DTO?看看這個:http:// stackoverflow。com/questions/6297322/dependency-injection-use-with-data-transfer-objects-dtos or http://programmers.stackexchange.com/questions/83091/use-dependency-injection-for-data-objects –
@CyrilDurand不幸的是,這是一個巨大的厄運類(其中很多)不是DTO對象。我試圖實現這樣的ioc結構項目,而不是一次做所有的事情,因此需要不簡化構造函數,因爲對象需要既注入又不注入,仍然功能相同。我非常接近解決方案,我會發布我提出的這個arvo。 – Spaceman