admin管理员组文章数量:1389726
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
)?
本文标签: cContainer validation when using the factory methods in NET Core DIStack Overflow
版权声明:本文标题:c# - Container validation when using the factory methods in .NET Core DI - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744641813a2617168.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论