通过autofac类寄存器将DbContext对象作为参数传递

时间:2015-10-16 13:15:43

标签: c# asp.net-mvc entity-framework autofac

我在MVC中有一个2层架构应用程序(Web和服务)。我在web项目的启动方法中注册了我的服务类,如下所示,

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;
    }
}

1 个答案:

答案 0 :(得分:1)

我认为您在MVC Controller中使用SearchService,因此您必须在那里创建ISearchService实例。在这种情况下,Autofac可以在您的控制器中进行构造函数注入。

public class ExampleController : Controller
{
    ISearchService _svc;

    public B2BHealthApiController(ISearchService s)
    {
        _svc = s;
    }
}

当Autofac创建ISearchService实例时,引擎定义ISearchService需要IApplicationDbContext的实例并自动创建它(相同的构造函数注入)。

所以你只需要说Autofac在哪里拿IApplicationDbContext和ISearchService实例。添加到您的Application_Start

builder.RegisterType<ApplicationDbContext>()                
            .As<IApplicationDbContext>()
            .InstancePerDependency();

builder.RegisterType<SearchService>()               
            .As<ISearchService>()
            .InstancePerRequest();