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?
Repository is asking for CustomerContext
directly in its constructor when you registered it as DbContext
so container doesn't know how to resolve CustomerContext
builder.RegisterType<CustomContext>().InstancePerRequest();
Register CustomContext
as IDbContext
and the parameter to MyRepository
's constructor should be an IDbContext
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With