Возможно ли использование DI Microsoft
для inject
и enum
?
Я получаю следующее исключение при создании экземпляра класса, который содержит enum
в constructor
.
InvalidOperationException: Невозможно разрешить службу для типа DependencyInjectionWithEnum.Domain.Types.TestType при попытке активировать DependencyInjectionWithEnum.Domain.Service.TestServiceВведите имя типа, 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);
}
}
Я получаю exception
при попытке вызвать конечную точку controller
через Swagger
.
Tech Stакк
- 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