Reputation: 9963
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?
Upvotes: 5
Views: 9645
Reputation: 247283
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();
Upvotes: 7
Reputation: 1591
Register CustomContext
as IDbContext
and the parameter to MyRepository
's constructor should be an IDbContext
.
Upvotes: 1