【问题标题】:Is it possible to instantiate a class which contains an injected enum是否可以实例化一个包含注入枚举的类
【发布时间】:2018-12-25 18:08:26
【问题描述】:

是否可以使用Microsoft 的 DI 到 injectenum

在实例化一个在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


【解决方案1】:

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

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

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

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

【讨论】:

  • 这就是我所追求的完美。谢谢
  • new 关键字引入了一个问题,如果TestService 注入了其他服务,所有服务都应该在TestType.First 旁边注入
  • @AhmadPayan sp 在工厂委托中是 IServiceProvider,可用于解决其他依赖项。 ActivatorUtilities 可用于与服务提供者一起创建实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
相关资源
最近更新 更多