DbContext没有被autofac注入

时间:2016-06-14 23:44:51

标签: c# entity-framework autofac

我遇到的问题是我的上下文没有在我的startup.cs中注册

我的完整启动看起来像

uvmyc

我的上下文类没什么特别的

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();
        RegisterApiTypes(builder);

        var config = new HttpConfiguration();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        //Register filters
        builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);
    }

    private static void RegisterApiTypes(ContainerBuilder builder)
    {
        builder.RegisterType<Logger>()
           .As<ILogger>()
           .InstancePerRequest();
        builder.RegisterType<ApplicationService>().As<IApplicationService>().InstancePerLifetimeScope();
        builder.RegisterType<CardRepository>().As<ICardRepository>().InstancePerLifetimeScope();
        //tried both of these without any luck
        //builder.RegisterType(typeof(CustomContext)).As(typeof(DbContext)).InstancePerRequest();
        //builder.RegisterType<CustomContext>().As<DbContext>().InstancePerRequest();

        builder.RegisterAssemblyTypes(Assembly.Load("MyApp.Data"))
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

    }

}

我尝试在标准庄园中注入上下文

public class CustomContext:DbContext
{
    public CustomContext() : base("DefaultConnection")
    {

    }
}

但是会抛出错误

  

没有任何构造函数与&#39; Autofac.Core.Activators.Reflection.DefaultConstructorFinder&#39;在类型&#39; MyApp.Data.Repository.MyRepository&#39;可以使用可用的服务和参数调用:\ r \ n无法解析参数&#39; MyApp.Data.CustomContext context&#39;构造函数&#39; Void .ctor(MyApp.Data.CustomContext)&#39;。&#34;

有没有其他人经历过这种行为?

2 个答案:

答案 0 :(得分:6)

当您将CustomerContext注册为DbContext时,存储库会在其构造函数中直接询问CustomerContext,因此容器不知道如何解析builder.RegisterType<CustomContext>().InstancePerRequest();

Prevent creation of multiple accounts with the same email address

答案 1 :(得分:1)

CustomContext注册为IDbContextMyRepository的构造函数的参数应为IDbContext