D
D
Dmitry Petrov2020-02-03 14:03:58
ASP.NET
Dmitry Petrov, 2020-02-03 14:03:58

Is type rebinding possible in an ASP.Net Core DI container?

The essence of the problem - there is an interface ITest.
It has an implementation based on the TestClass1 class.
In the ConfigureServices method, the binding is created as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ITest, TestClass1>();
}

Once launched, the application consumes the dependency instance based on TestClass1 by calling IServiceProvider.GetService().
What happens if, at runtime, the application needs to rebind the interface from the TestClass1 type to the TestClass2 type, which also implements the ITest interface? What approach is used in this case?
How to approach this situation, if in some cases the binding of a singleton object must be strict, without the possibility of rebinding, and in some cases rebinding is allowed.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2020-02-03
@petermzg

Set it to type Transient and return the required object instance in the factory method

serviceCollection.AddTransient<ITest>((serviceProvider) =>
{
     return (<условие>) ? new TestClass1() : new TestClass2();
});

R
Roman, 2020-02-03
@yarosroman

As far as I know, all dependencies are determined at the time of launch and cannot be overridden, the built-in container does not provide such an opportunity.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question