最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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)?

发布评论

评论列表(0)

  1. 暂无评论