Search code examples
c#wpfdependency-injectionprismdryioc

How to register a class to IoC in Prism


I write an application with WPF. I use the Prism library with IoC as Prism.DryIoC. I have an AppDbContext.cs class to declare the connection string to the database (here is MongoDB)

public class AppDbContext : BaseMongoRepository
{
    public AppDbContext(string connectionString, string databaseName = null) : base(connectionString, databaseName)
    {
    }
}

I have a class MyService.cs that uses the AppDbContext class, I declare in the constructor. public class MyService : IMyService { private AppDbContext _dbContext;

    public IdentifierRepository(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public void AddCustomer(Customer model)
    {
        // Some code....
        _dbContext.Add(model);
    }
}

In the App.xaml.cs class I override the method

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterSingleton<IAuthenticationService, AuthenticationService>();


    // MongoDB
    var connectionString = SharedCommon.LocalAppSettings.Database.ConnectionString;
    var database         = SharedCommon.LocalAppSettings.Database.DatabaseName;

    // How to register class MyService.cs here?
    // I dont known.
    containerRegistry<MyService>(() => new MyService(new AppDbContext(connectionString, database))); // Wrong code
}

Solution

  • You can find all the registration methods here.

    For singleton MyService:

    var myService = new MyService(new AppDbContext(connectionString, database)));
    containerRegistry.RegisterInstance(myService);
    

    For multiple instances you could use a factory instead.

    public class MyServiceFactory
    {
        private readonly AppDbContext appDbContext;
        public MyServiceFactory(AppDbContext appDbContext)
        {
            this.appDbContext = appDbContext;
        }
    
        public MyService Create() => new MyService(appDbContext);
    }
    

    Register the instance of the factory:

    var context = new AppDbContext(connectionString, database);
    var factory = new MyServiceFactory(context);
    
    containerRegistry.RegisterInstance(factory);
    

    Then create your service instance:

    var factory = container.Resolve<MyServiceFactory>();
    var service = factory.Create();