I am receiving this error message from Autofac;:
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyService`1[MyContext]' can be invoked with the available services and parameters: Cannot resolve parameter 'MyContext context' of constructor 'Void .ctor(MyContext)'.
The error occurs on this line of code (also shown in the code below):
IMyService myService = container.Resolve<IMyService>(); // error here
I am interested to note that when I include this line in my registrations, everything works:
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
The fact that it all works when I register AnyConcreteType... leads me to believe I am not not registering something. My question is what am I not registering? The error message appears to name MyContext as the culprit but clearly I am registering it as shown below.
I really dont want to use the AnyConcreteType... catch all because I want to explicity register only the the classes I need.
My service is constructed like this:
public class MyService<T> : BaseService<T>, IMyService where T:DbContext,IMyContext
{
public MyService(T context) : base(context)
{
}
}
MyService derives from BaseService:
public abstract class BaseService<T> : IDisposable where T:DbContext, IMyContext
{
internal T db;
public BaseService(T context)
{
db = context;
}
}
MyContext is passed to MyService and is constructed like this:
public partial class MyContext : DbContext, IMyContext
{
public MyContext(INamedConnectionString conn)
: base(conn.ConnectionString)
{
Configuration.ProxyCreationEnabled = false;
}
}
Here is NamedConnectionString
public class NamedConnectionString : INamedConnectionString
{
public string ConnectionString { get; set; }
}
Here is how I register the above:
builder.RegisterType<MyService<MyContext>>().As<IMyService>();
builder.RegisterType<NamedConnectionString>().As<INamedConnectionString>().SingleInstance();
builder.RegisterType<MyContext>().As<IMyContext>().InstancePerLifetimeScope();
builder.RegisterType<DbContext>(); // is this necessary??
And here is how I call it:
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
INamedConnectionString namedConnectionString = container.Resolve<INamedConnectionString>();
namedConnectionString.ConnectionString = myConnectionString;
IMyService myService = container.Resolve<IMyService>(); // error here