1
我在MVC中有2层体系结构应用程序(Web和服务)。我已经注册了我的服务类在类似下面的Web项目的启动方法,将DbContext对象作为参数传递给autofac类寄存器
protected void Application_Start()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterControllers(typeof(MvcApplication).Assembly);
containerBuilder.RegisterModelBinders(Assembly.GetExecutingAssembly());
containerBuilder.RegisterModelBinderProvider();
containerBuilder.RegisterType<SearchService>().As<ISearchService>();
var container = containerBuilder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
我已经创建了接口的DbContext,像下面
public interface IApplicationDbContext
{
DbSet<Customer> Customers { get; set; }
}
,我有一个DbContextClass这样,
public class ApplicationDbContext :
IdentityDbContext<User, Role, Guid, UserLogin, UserRole, UserClaim>,
IApplicationDbContext
{
public ApplicationDbContext() : base("DefaultConnection")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<ApplicationDbContext>());
}
}
这里我的问题是,我想的DbContext对象作为参数传递到下面的服务类,这样
public class SearchService : ISearchService
{
IApplicationDbContext _dbContext;
public QueueService(IApplicationDbContext context)
{
_dbContext = context;
}
}
你只需要设置你的DbContext的绑定,我不知道如何使用Autofac,但我已经添加了Autofac标签给你们,希望有人会回答。看起来你已经设置了你的容器来扫描当前的程序集,但是你希望它稍后为你的DbContext扫描你的服务层/数据,以便它可以被解析。 – Luke
或者定义一个'IDbContextFactory',您可以在'SearchService'构造函数中使用它来创建所需上下文的实例。无论哪种方式,您需要在容器中注册一些东西,以便容器可以连接所有必需的接口及其实现。 – Maarten
你解决了吗? – Eonasdan