Can a simple injector register multiple instances of the same type using different constructor parameters?

I am exploring the use of Simple Injector as a dependency injector. I am intentionally going to use different instances of the class MemoryCacheas nested dependencies:

public class WorkflowRegistrationService : IWorkflowRegistrationService
{
    public WorkflowRegistrationService( MemoryCache cache ) {}
}

public class MigrationRegistrationService : IMigrationRegistrationService
{
    public MigrationRegistrationService( MemoryCache cache ) {}
}

If I were updating classes, I would do something like the following to create different caches for each of these services:

var workflowRegistrationCache = new MemoryCache("workflow");
var migrationRegistrationCache = new MemoryCache("migration");

How can this be done with a simple injector? Essentially, I need to tell him to use specific instances when introduced into certain types.

+4
source share
1 answer

, , :

var workflowRegistrationCache = new MemoryCache("workflow");

container.Register<IWorkflowRegistrationService>(
    () => new WorkflowRegistrationService(workflowRegistrationCache));

var migrationRegistrationCache = new MemoryCache("migration");

container.Register<IMigrationRegistrationService>(
    () => new MigrationRegistrationService(
        container.GetInstance<ISomeService>(),
        migrationRegistrationCache));

. , , :

var workflowRegistrationCache = new MemoryCache("workflow");
var migrationRegistrationCache = new MemoryCache("migration");

container.RegisterWithContext<MemoryCache>(context =>
{
   return context.ServiceType == typeof(IWorkflowRegistrationService)
       ? workflowRegistrationCache 
       : migrationRegistrationCache;
});

container.Register<IWorkflowRegistrationService, WorkflowRegistrationService>();
container.Register<IMigrationRegistrationService, MigrationRegistrationService>();

WorkflowRegistrationService MigrationRegistrationService , .

, , . fooobar.com/questions/1510262/... .

+4

Source: https://habr.com/ru/post/1541338/


All Articles