C# 基于ctor参数的Autofac构件构建
是否可以注册组件,以便根据构造函数参数解析组件C# 基于ctor参数的Autofac构件构建,c#,autofac,C#,Autofac,是否可以注册组件,以便根据构造函数参数解析组件 public interface IRepository<T>{} public interface IMyRepo {} public class MyRepo : IRepository<TEntity>, IMyRepo { public MyRepo(IDbConnection connection){} public MyRepo(){} } // lots of other repositor
public interface IRepository<T>{}
public interface IMyRepo {}
public class MyRepo : IRepository<TEntity>, IMyRepo
{
public MyRepo(IDbConnection connection){}
public MyRepo(){}
}
// lots of other repositories...
public class Global
{
public void BuildDIContainer()
{
var builder = new ContainerBuilder();
var assembly = Assembly.GetExecutingAssembly();
//any class that implements IRepository<T> is instance per request
builder.RegisterAssemblyTypes(typeof (IRepository<>).Assembly, assembly)
.AsClosedTypesOf(typeof (IRepository<>))
.AsImplementedInterfaces().InstancePerHttpRequest();
//any class that implements IRepository<T> with IDbConnection as ctor parameter is instance per dependency
builder.RegisterAssemblyTypes(typeof(IRepository<>).Assembly, assembly)
.UsingConstructor(typeof(IDbConnection)) // <-- ??
.AsClosedTypesOf(typeof(IRepository<>))
.AsImplementedInterfaces().InstancePerDependency();
//............
//per dependency
var repo1 = ComponentContext.Resolve<IMyRepo>(new NamedParameter("connection", new SqlConnection("...")));
//per request
var repo2 = ComponentContext.Resolve<IMyRepo>();
}
}
使用.InstancePerLifetimeScope仅注册MyRepo一次
当在web应用程序中使用.InstancePerHttpRequest时,这将相当于.InstancePerHttpRequest。我假设在这种情况下,您不需要调用没有参数的Resolve,而只需要接受注入的依赖项
然后,不是在传递参数时直接解析IMyRepo,而是解析:
这将有一个额外的优势,即确保使用自定义连接解析的存储库被正确释放
希望这能有所帮助,对你的情况做一些假设,如果有什么不清楚的地方,请告诉我
using (var repoWithParam = ComponentContext.Resolve<Owned<IMyRepo>>(
new NamedParameter("connection", ...))){
// Use repoWithParam.Value here
}