![](/img/trans.png)
[英]how to pass generic interface in constructor of a class with type of that class with autofac
[英]How to pass a specific implementation of a class to a generic in Autofac
我有一個通用類EfRepository<>
,它是接口IRepository<>
。 此類將DbContext
作為其構造函數的參數。 我需要精確注入DbContext
的特定子類,即ApplicationDbContext
。 如何在Autofac中做到這一點?
這就是我所擁有的,我想要的是:
builder.RegisterGeneric(typeof(EfRepository<>))
.As(typeof(IRepository<>))
.InstancePerDependency();
//The following line doesn't even compile but perhaps it can make my question clearer
builder.Register(c => new EfRepository<>(new ApplicationDbContext()))
.As(typeof(EfRepository<>))
.InstancePerDependency();
您無需執行任何特殊操作,只需將ApplicationDbContext
注冊為DbContext
builder.RegisterGeneric(typeof(EfRepository<>))
.As(typeof(IRepository<>));
builder.Register<ApplicationDbContext>()
.As<DbContext>();
如果要為EfRepository<>
注冊特定的DbContext
,可以使用WithParameter
方法
builder.RegisterGeneric(typeof(EfRepository<>))
.As(typeof(IRepository<>))
.WithParameter((pi, c) => pi.ParameterType == typeof(DbContext),
(pi, c) => c.ResolveNamed<DbContext>("application"));
builder.Register<ApplicationDbContext>()
.Named<DbContext>("application");
我使用命名注冊來受益於Autofac
實例化,而不是直接實例化。
您可以在此處找到更多信息: 傳遞參數進行注冊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.