V
V
Vlad2022-01-12 13:24:10
.NET
Vlad, 2022-01-12 13:24:10

How to register two identical services in DI?

The question is probably simple, but I did not master it right off the bat. Let's say I have a Singletone service, and I want to register another one so that they differ in "names". Usually, if two service classes implement the same interface, then a DependencyResolver is created, which rummages through IEnumerable and finds the required type, but what if both services are identical and differ only in "names"? Here, of course, the question arises "what for a goat button accordion", but it's just interesting, in particular, what to do if I have two identical databases with different connectionString, but the same DbContext.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
oleg_ods, 2022-01-13
@oleg_ods

If the interfaces are the same, you can register a factory instead of a service, which will already return the necessary implementation

V
Vasily Bannikov, 2022-01-12
@vabka

It seems that there are no named instances in the standard msdi. So here are two options how I would do it:
1. I would make two heirs of this common DbContext
2. I would use a third-party DI. For example SimpleInjector or Autofac

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question