Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 仅将服务限制为单例_C#_Asp.net_Dependency Injection - Fatal编程技术网

C# 仅将服务限制为单例

C# 仅将服务限制为单例,c#,asp.net,dependency-injection,C#,Asp.net,Dependency Injection,有没有办法使一个服务在ASP.NET中只能作为单例使用?反之亦然,不允许将其用作单例 services.AddSingleton();//这应该行得通 services.AddTransient();//这将抛出一个错误 services.addScope();//这将抛出一个错误 或者 services.AddSingleton();//这将抛出一个错误 services.AddTransient();//这应该行得通 services.addScope();//这应该行得通 使用servi

有没有办法使一个服务在ASP.NET中只能作为单例使用?反之亦然,不允许将其用作单例

services.AddSingleton();//这应该行得通
services.AddTransient();//这将抛出一个错误
services.addScope();//这将抛出一个错误
或者

services.AddSingleton();//这将抛出一个错误
services.AddTransient();//这应该行得通
services.addScope();//这应该行得通

使用service.addYourOwnSingleton可以编写Roslyn分析器来显示警告甚至编译错误。当
AddTransient
AddScoped
与实现此标记接口的类一起使用时,可以创建一个特殊接口,例如IOnlyRegistersAsSingleton,并使Roslyn分析器显示编译错误。但我不确定这是否值得。使用service.addyourownsingleton是可能的。您可以编写Roslyn分析器来显示警告甚至编译错误。当
AddTransient
AddScoped
与实现此标记接口的类一起使用时,可以创建一个特殊接口,例如IOnlyRegistersAsSingleton,并使Roslyn分析器显示编译错误。但我不确定这是否值得。