Is it possible to instantiate a class which contains an injected enum

Viewed 1747

Is it possible using Microsoft's DI to inject an enum?

I am getting the following exception when instantiating a class which contains a enum in the constructor.

InvalidOperationException: Unable to resolve service for type DependencyInjectionWithEnum.Domain.Types.TestType while attempting to activate DependencyInjectionWithEnum.Domain.Service.TestService Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)

I have the following enum:

/// <summary>
/// This is a test enum which is injected into the TestService's constructor
/// </summary>
public enum TestType
{
    First,
    Second,
    Third,
    Forth,
    Fifth
}

Which gets injected into the following

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();
        }
    }
}

Then in Startup.cs I add the TestService to the 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" });
    });
}

Finally I inject my TestService into my controller

[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);
    }
}

I get the exception when attempting to call the controller's endpoint via Swagger.

Tech Stack

- 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 Answers

Is it possible using Microsoft's DI to inject an enum?

YES

Out of the box the enum can be added with a factory delegate when registering the service at start up

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

When injecting TestService into any dependents the container will use the factory delegate to resolve the class and its dependencies.

Related