【发布时间】:2018-12-25 18:08:26
【问题描述】:
是否可以使用Microsoft 的 DI 到 inject 和 enum?
在实例化一个在constructor 中包含enum 的类时出现以下异常。
无效操作异常: 无法解析类型 DependencyInjectionWithEnum.Domain.Types.TestType 的服务 尝试激活 DependencyInjectionWithEnum.Domain.Service.TestService 时 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] 参数, bool throwIfCallSiteNotFound)
我有以下枚举:
/// <summary>
/// This is a test enum which is injected into the TestService's constructor
/// </summary>
public enum TestType
{
First,
Second,
Third,
Forth,
Fifth
}
注入到以下
public class TestService
{
private readonly TestType testType;
/// <summary>
/// Here I am injecting an enum called TestType
/// </summary>
/// <param name="testType"></param>
public TestService(TestType testType)
{
this.testType = testType;
}
/// <summary>
/// This is a dummy method.
/// </summary>
/// <returns></returns>
public string RunTest()
{
switch(testType.ToString().ToUpperInvariant())
{
case "First":
return "FIRST";
case "Second":
return "SECOND";
case "Third":
return "THIRD";
case "Forth":
return "FORTH";
case "Fifth":
return "FIFTH";
default:
throw new InvalidOperationException();
}
}
}
然后在 Startup.cs 中将 TestService 添加到 ServiceCollection
public void ConfigureServices(IServiceCollection services)
{
//mvc service
services.AddMvc();
// Setup the DI for the TestService
services.AddTransient(typeof(TestService), typeof(TestService));
//data mapper profiler setting
Mapper.Initialize((config) =>
{
config.AddProfile<MappingProfile>();
});
//Swagger API documentation
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "DependencyInjectionWithEnum
API", Version = "v1" });
});
}
最后我将我的 TestService 注入到我的控制器中
[Route("api/[controller]")]
public class TestController : ControllerBase
{
private readonly TestService testService;
/// <summary>
/// Here I am injecting a TestService. The TestService is the class from which I am attempting to inject an enum
/// </summary>
/// <param name="testService"></param>
public TestController(TestService testService)
{
this.testService = testService;
}
/// <summary>
/// Dummy get
/// </summary>
/// <returns></returns>
[HttpGet]
[ProducesResponseType(200, Type = typeof(string))]
public IActionResult Get()
{
var testResult = testService.RunTest();
return Ok(testResult);
}
}
我在尝试通过Swagger 调用controller 的端点时得到exception。
技术栈
- Visual Studio v15.9.4 C# v7.3
- Project Target Framework .NET Core 2.2
- NuGet Packages
- Microsoft.AspNetCore v2.2.0
- Microsoft.AspNetCore.Mvc v2.2.0
- Microsoft.Extensions.DependencyInjection v2.2.0
【问题讨论】:
-
已知类型如何注入
-
一切皆有可能,尽管不同寻常。您的枚举在哪里注册到 DI 容器?我在 ConfigureServices 中看不到它。
-
我的意思是你需要类似 services.AddTransient(TestService) 的东西,但是对于枚举。 :-)
-
开箱即用的枚举可以在注册服务时添加到工厂委托中,但仍然不确定您要实现的目标是什么,因为这看起来像XY problem。 .
-
@AlKepp 你是对的。在我的示例中,我没有注入它。我最初尝试“services.AddTransient(typeof(TestService), typeof(TestService)”注入它失败了另一个异常。
标签: c# dependency-injection enums