我有以下场景,依赖注入发生在下面给出的类定义之外,因此我无法访问类中的构建器对象。问题是DbContext被映射到两个类,因为我需要使用两个不同的数据库。为了创建SomeClass,需要实例化MyRepository和MyOtherRepository,但要做到这一点需要2个不同的DbContexts。事情失败的地方因为Autofac只采用DbContext映射到MyOtherContext的最后一个映射。非常感谢您解决此问题的任何帮助,谢谢! 如果需要更多信息,请告诉我。
public class DependencyResolver : IDependencyResolver
{
builder.RegisterType<MyContext>().As<DbContext>().InstancePerLifetimeScope();
builder.RegisterType<MyOtherContext>().As<DbContext>().InstancePerLifetimeScope();
builder.RegisterType<RepositoryManager.MyRepository>().As<Types.Repository.IMyRepository>().InstancePerDependency();
builder.RegisterType<RepositoryManager.MyOtherRepository>().As<Types.Repository.IMyOtherRepository>().InstancePerDependency();
}
下面的类定义
public class SomeClass
{
public SomeClass(IMyRepository myRepository, IMyOtherRepository myOtherRepository)
{
// Code
}
}
public class MyContext : DbContext
{
// Code
}
public class MyOtherContext : DbContext
{
// Code
}
public class MyRepository : IRepository
{
public MyRepository (DbContext context) : base(context)
{
// Code
}
}
public class MyOtherRepository : IRepository
{
public MyOtherRepository (DbContext context) : base(context)
{
// Code
}
}
答案 0 :(得分:3)
试试这个answer。基本上您正在寻找Autofac的Named and Keyed Services功能。我更喜欢resolving with attributes approach
所以如果你注册这样的上下文:
var builder = new ContainerBuilder();
builder
.RegisterType<MyContext>()
.As<DbContext>()
.WithMetadata("EFContext", "My");
builder
.RegisterType<MyRepository>()
.AsImplementedInterfaces();
builder
.RegisterType<MyOtherContext>()
.As<DbContext>()
.WithMetadata("EFContext", "Other");
builder
.RegisterType<MyOtherRepository>()
.AsImplementedInterfaces();
您应该可以将它们与(非强类型)元数据一起使用:
public class SomeClass
{
private readonly IMyRepository _myRepository;
private readonly IMyOtherRepository _myOtherRepository;
public SomeClass(IMyRepository myRepository, IMyOtherRepository myOtherRepository)
{
_myRepository = myRepository;
_myOtherRepository = myOtherRepository;
}
public string SayHello()
{
return $"Hello from {_myRepository.ContextName()} and {_myOtherRepository.ContextName()}";
}
}
public interface IMyOtherRepository
{
string ContextName();
}
public interface IMyRepository
{
string ContextName();
}
public class MyContext : DbContext
{
// Code
}
public class MyOtherContext : DbContext
{
// Code
}
public class MyRepository : IMyRepository
{
private readonly IEnumerable<Meta<DbContext>> _context;
public MyRepository(IEnumerable<Meta<DbContext>> context)
{
_context = context;
// Code
}
public string ContextName() => _context.First(x => x.Metadata["EFContext"].Equals("My")).Value.GetType().Name;
}
public class MyOtherRepository : IMyOtherRepository
{
private readonly IEnumerable<Meta<DbContext>> _context;
public MyOtherRepository(IEnumerable<Meta<DbContext>> context)
{
this._context = context;
// Code
}
public string ContextName() => _context.First(x => x.Metadata["EFContext"].Equals("Other")).Value.GetType().Name;
}