[英]autofac - register generic on non generic abstract class
autofac-在非通用抽象類上注冊通用
我有以下課程結構..
public class DataContext<TEntityModel> : DataContextBase
where TEntityModel : IEntity
{
public DataContext(string databaseName, string serverName = "localhost") :
base(databaseName, serverName)
{
}
}
public abstract class Repository<TEntityModel> : IRepository<TEntityModel>
where TEntityModel : Entity
{
protected MongoRepositoryBase(DataContextBase ctx)
{
this.DBContext = ctx;
}
}
public class CustomerRepository : Repository<Customer>
{
public CustomerRepository(DataContext<Customer> ctx)
: base(ctx)
{
}
}
我嘗試了以下操作,但得到“類型'Repository 2' does not implement the interface 'IRepository
1'”。
builder.RegisterAssemblyTypes(typeof(DataContextBase).Assembly).AsClosedTypesOf(typeof(DataContext<>));
如何為DataContext進行IoC注冊?
AsClosedTypesOf
方法無法幫助您注冊DataContext<>
,它可以幫助您注冊IRepository<T>
。
無需手動注冊所有存儲庫
builder.RegisterType<CustomerRepository>().As<IRepository<Customer>>();
builder.RegisterType<InvoiceRepository>().As<IRepository<Invoice>>();
...
您將可以全部注冊一次:
builder.RegisterAssemblyTypes(typeof(IRepository<>).Assembly).AsClosedTypesOf(typeof(IRepository<>));
要以通用方式注冊DataContext<>
,可以使用RegistrationSource
:
public class DataContextRegistrationSource : IRegistrationSource
{
public Boolean IsAdapterForIndividualComponents
{
get { return true; }
}
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
if (service == null)
{
throw new ArgumentNullException("service");
}
if (registrationAccessor == null)
{
throw new ArgumentNullException("registrationAccessor");
}
IServiceWithType ts = service as IServiceWithType;
if (ts == null || !(ts.ServiceType.IsGenericType && ts.ServiceType.GetGenericTypeDefinition() == typeof(DataContext<>)))
{
yield break;
}
yield return RegistrationBuilder.ForType(ts.ServiceType)
.AsSelf()
.WithParameter(new NamedParameter("databaseName", "test"))
.WithParameter(new NamedParameter("serverName", "test2"))
.CreateRegistration();
}
}
然后
builder.RegisterSource(new DataContextRegistrationSource());
您現在可以解析IRepository<Customer>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.