I use unit of work pattern with entityFramework code first. Now I want to use Autofac to register UnitOfWork, Repositories and My dbContext.
This Is my UnitOfWork
code:
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext _context;
public UnitOfWork(DbContext context)
{
_context = context;
Contact = new ContractRepository(context);
}
public void Dispose()
{
_context.Dispose();
GC.SuppressFinalize(_context);
}
public IContactRepository Contact { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
}
and this is my repository:
public class Repository<Entity> : IRepository<Entity> where Entity : class
{
protected readonly DbContext _noteBookContext;
public Repository(DbContext noteBookContext)
{
_noteBookContext = noteBookContext;
}
public void Add(Entity entity)
{
_noteBookContext.Set<Entity>().Add(entity);
}
}
and this is one of my repositories:
public class ContractRepository: Repository<Contact>,IContactRepository
{
public ContractRepository(DbContext noteBookContext) : base(noteBookContext)
{
}
public DbContext NotebookContext
{
get
{
return _noteBookContext;
}
}
}
and this is my db context class:
public class NoteBookContext:DbContext
{
public NoteBookContext(string connectionstring):base(connectionstring)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ContactConfig());
modelBuilder.Configurations.Add(new PhoneConfig());
modelBuilder.Configurations.Add(new PhoneTypeConfig());
modelBuilder.Configurations.Add(new GroupConfig());
base.OnModelCreating(modelBuilder);
}
public DbSet<Contact> Contacts { get; set; }
public DbSet<Phone> Phones { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<PhoneType> PhoneTypes { get; set; }
}
Now I want to register UnitOfWork with constructor (a constructor like this: )
var uow = new UnitOfWork(new NotebookdbContext("connectionstring"));
Note that NoteBookContext is my entity framework model.
I write registration but I got Error:
var builder = new ContainerBuilder();
builder.RegisterType<NoteBookContext>()
.As<DbContext>();
builder.RegisterType<UnitOfWork>()
.UsingConstructor(typeof(DbContext))
.As<IUnitOfWork>();
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
Container container = builder.Build();
This is my error:
An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll Additional information: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'DataLayer.NoteBookContext' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.String connectionstring' of constructor 'Void .ctor(System.String)'.
Edit 2 :
after help from Cyril Durand's answer I write following registering config:
var builder = new ContainerBuilder();
builder.RegisterType<ConnectionStringProvider>().As<IConnectionStringProvider>();
builder.RegisterType<NoteBookContext>().As<DbContext>().WithParameter((pi, c) => pi.Name == "connectionstring",
(pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString);
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().WithParameter(ResolvedParameter.ForNamed<DbContext>("connectionstring"));
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
and In my code :
using (var scope = DependencyInjection.Container.BeginLifetimeScope())
{
var ConnectionString = scope.Resolve<IConnectionStringProvider>();
ConnectionString.ConnectionString = "Context";
var uw = scope.Resolve<IUnitOfWork>();
var a =uw.Contact.GetAll();
}
but I got Error again:
An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll
Additional information: An exception was thrown while invoking the constructor 'Void .ctor(System.String)' on type 'NoteBookContext'.
can everyone help me?
The error message :
An unhandled exception of type
Autofac.Core.DependencyResolutionException
occurred in Autofac.dll Additional information: None of the constructors found withAutofac.Core.Activators.Reflection.DefaultConstructorFinder
on typeDataLayer.NoteBookContext
can be invoked with the available services and parameters:Cannot resolve parameter
System.String connectionstring
of constructorVoid .ctor(System.String)
.
tells you that Autofac can't create a NoteBookContext
because it can't resolve a parameter named connectionstring
of type String
.
Your NoteBookContext
implementation needs a connectionstring, Autofac can't know it without you telling it. When you register the NoteBookContext
you will have to specify the connectionstring :
builder.RegisterType<NoteBookContext>()
.As<DbContext>()
.WithParameter("connectionstring", "XXX");
Another solution with dynamic resolution and a IConnectionStringProvider
interface :
public interface IConnectionStringProvider
{
public String ConnectionString { get; }
}
and registration :
builder.RegisterType<ConnectionStringProvider>()
.As<IConnectionStringProvider>()
.InstancePerLifetimeScope();
builder.RegisterType<NoteBookContext>()
.As<DbContext>()
.WithParameter((pi, c) => pi.Name == "connectionstring",
(pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString)
.InstancePerLifetimeScope();