简体   繁体   中英

How to register singleton on Autofac

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.

I couldn't figure out that why are you injecting manually IMongoDataContext when registering DemoRepository . Is it not main purpose of Inversion of Control Tool ? I think, you should change your approach;

builder.RegisterType<DemoRepository>().As<IDemoRepository>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM