I am using Autofac
for dependency injection in my .Net Core 2.0
web application. I am new to Autofac
and dependency injection concepts.
Now, I want to register a singleton in DI
and resolve it in DI container.
C# Code [Interface]
public interface IMongoDbContext
{
IMongoDatabase Database { get; }
}
Class
public class MongoDbContext : IMongoDbContext
{
public MongoDbContext(string connectionString, string databaseName);
public string DatabaseName { get; }
public IMongoDatabase Database { get; }
public string ConnectionString { get; }
}
Repository Class
public class DemoRepository : IDemoRepository
{
public DemoRepository(IMongoDataContext context)
{
}
}
Now, in .Autofac
builder.Register(c => new MongoDbContext(dbConnectionString, dataBaseName)).As<IMongoDbContext>().SingleInstance();
//dbConnectionString and dataBaseName are string variables declared above.
// and then to Resolve it
builder.Register(c => new DemoRepository(c.Resolve<IMongoDbContext>)).As<IDemoRepository>();
// but in above line it shows error at `c.Resolve<IMongoDbContext>` it shows `cannot convert from 'method group' to 'IMongoDbContext'`
Can anyone help me to resolve this. I am new to autofac and dependency Injection, I want to know how I can register Singleton in autofac.
Any help would be highly appreciated ...!!
Thanks
c.Resolve<IMongoDbContext>
should be:
c.Resolve<IMongoDbContext>()
You forgot to call / invoke the function.