简体   繁体   中英

DbContext not getting injected by autofac

I am having a problem where my context in not registering within my startup.cs

My complete startup looks like

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();

    }

}

My context class is nothing special

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

    }
}

I try to inject the context in a standard manor

public MyRepository(CustomContext context)
{
    _context = context;
}

However an error is thrown

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyApp.Data.Repository.MyRepository' can be invoked with the available services and parameters:\\r\\nCannot resolve parameter 'MyApp.Data.CustomContext context' of constructor 'Void .ctor(MyApp.Data.CustomContext)'."

Has anyone else experienced this kind of behavior?

当您将其注册为DbContext时,存储库直接在其构造函数中要求CustomerContext ,因此容器不知道如何解析CustomerContext

builder.RegisterType<CustomContext>().InstancePerRequest();

CustomContext注册为IDbContext并且MyRepository的构造函数的参数应该是IDbContext

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM