是否可以实例化包含注入枚举的类

时间:2018-12-25 18:08:27

标签: c# dependency-injection enums

是否可以使用Microsoft的DI来injectenum

实例化在enum中包含constructor的类时遇到以下异常。

  

InvalidOperationException:           无法解析类型DependencyInjectionWithEnum.Domain.Types.TestType的服务           在尝试激活DependencyInjectionWithEnum.Domain.Service.TestService时       Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType,Type ImplementationType,CallSiteChain callSiteChain,ParameterInfo [] parameters,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

技术堆栈

- 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

1 个答案:

答案 0 :(得分:3)

  

是否可以使用Microsoft的DI注入枚举?

在启动时注册服务时,开箱即用工厂委托可以添加枚举

// Setup the DI for the TestService
services.AddTransient<TestService>(sp => new TestService(TestType.First));

TestService注入任何依赖项时,容器将使用工厂委托来解析类及其依赖项。