c# - Container validation when using the factory methods in .NET Core DI - Stack Overflow

Let's say that we have the following 2 services:class OtherService : IOtherService {}public cla

Let's say that we have the following 2 services:

class OtherService : IOtherService 
{
}

public class ParameterizedService
{
    public ParameterizedService(IOtherService otherService) 
        => Console.WriteLine("Parameterless constructor");

    public ParameterizedService(IOtherService otherService, string parameter) 
        => Console.WriteLine($"Constructor with a parameter: {parameter}");
}

Then we use the following code for the registration:

var services = new ServiceCollection();
// we fet to register IOtherService, so can't instantiate
// the ParameterizedService
// services.AddSingleton<IOtherService, OtherService>();
services.AddSingleton<ParameterizedService>();

// this next line this will throw an error
using var provider = services.BuildServiceProvider(new ServiceProviderOptions
{
    ValidateOnBuild = true,
});

Here we "fet" to register IOtherService and the container validation will fail: the call to the .BuildServiceProvider() will throw the exception:

Error while validating the service descriptor 'ServiceType: ParameterizedService
Lifetime: Singleton
ImplementationType: ParameterizedService':
No constructor for type 'ParameterizedService' can be instantiated using services from the service container and default values.

And this is perfect!

But if we want to use the other constructor of the ParameterizedService, which takes a string parameter, then we are forced to use a factory method like this:

var services = new ServiceCollection();

// we fet to register IOtherService, so can't instantiate
// the ParameterizedService
// services.AddSingleton<IOtherService, OtherService>();
services.AddSingleton<ParameterizedService>(sp => 
{
    return ActivatorUtilities.
           CreateInstance<ParameterizedService>(sp, "Hello from the factory");
});

// no exception on the next line
using var provider = services.BuildServiceProvider(new ServiceProviderOptions
{
    ValidateOnBuild = true,
});

And in this implementation (where we still "fet" to register the IOtherService) the BuildServiceProvider() will succeed without any errors. But the app will crash later when someone will try to really instantiate the ParameterizedService from the container. And that is disappointing.

Is there a way to tell the container that ParameterizedService depends on IOtherService in this case so that the validation still works despite the using of the factory method? Or is there another way to write the registration so that the validation will still work (but still retains the ability to explicitly pass the value for the parameter)?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744641813a4585487.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信