我目前有以下代码来创建两个工厂。
//Composition Root
ICatalogFilterRepository catalogFilterRepositoryRedis = new RedisCatalogFilterRepository();
ICatalogFilterRepository catalogFilterRepositorySql = new SqlCatalogFilterRepository();
IFilterCreatorService filterCreatorServiceRedis = new FilterCreatorService(catalogFilterRepositoryRedis);
IFilterCreatorService filterCreatorServiceSql = new FilterCreatorService(catalogFilterRepositorySql);
IFilterCreatorServiceFactory filterCreatorServiceFactory = new FilterCreatorServiceFactory(filterCreatorServiceRedis, filterCreatorServiceSql);
ICatalogService catalogServiceCs = new CommerceServerWsService();
ICatalogService catalogServiceRedis = new CatalogService(catalogFilterRepositoryRedis);
ICatalogService catalogServiceSql = new CatalogService(catalogFilterRepositorySql);
ICatalogServiceFactory commerceServerCatalogServiceFactory = new CatalogServiceFactory(catalogServiceCs, catalogServiceRedis, catalogServiceSql);
现在我想使用Unity,所以我在Unity上面注册如下:
//Configure the Unity container.
IUnityContainer myContainer = new UnityContainer()
.RegisterType<ICatalogFilterRepository, RedisCatalogFilterRepository>("Redis")
.RegisterType<ICatalogFilterRepository, SqlCatalogFilterRepository>("Sql")
.RegisterType<IFilterCreatorService, FilterCreatorService>()
.RegisterType<IFilterCreatorServiceFactory, FilterCreatorServiceFactory>()
.RegisterType<ICatalogService, CommerceServerWsService>()
.RegisterType<ICatalogService, CatalogService>()
.RegisterType<ICatalogServiceFactory, CatalogServiceFactory>();
IFilterCreatorServiceFactory filterCreatorServiceFactory = myContainer.Resolve<IFilterCreatorServiceFactory>();
ICatalogServiceFactory commerceServerCatalogServiceFactory = myContainer.Resolve<ICatalogServiceFactory>();
但它不起作用。我得到一个例外。在某种程度上,我需要告诉Unity在工厂构造函数中注入哪些具体类。是否使用覆盖?请帮我解决这个问题。 FilterCreatorServiceFactory:
public class FilterCreatorServiceFactory : IFilterCreatorServiceFactory
{
private readonly IFilterCreatorService _filterCreatorServiceRedis;
private readonly IFilterCreatorService _filterCreatorServiceSql;
public FilterCreatorServiceFactory(IFilterCreatorService filterCreatorServiceRedis, IFilterCreatorService filterCreatorServiceSql)
{
if (filterCreatorServiceRedis == null)
throw new ArgumentNullException("filterCreatorServiceRedis");
if (filterCreatorServiceSql == null)
throw new ArgumentNullException("filterCreatorServiceSql");
_filterCreatorServiceRedis = filterCreatorServiceRedis;
_filterCreatorServiceSql = filterCreatorServiceSql;
}
public IFilterCreatorService Create(string filterRepositoryName)
{
if (filterRepositoryName == "Redis")
return _filterCreatorServiceRedis;
if (filterRepositoryName == "Sql")
return _filterCreatorServiceSql;
throw new Exception("filterRepositoryName " + filterRepositoryName + " is not valid");
}
}