Search code examples
.netunity-container

UnityDependencyResolver can't resolve Enum


I work with .Net Framework 4.7 and UnityDependencyResolver. My customer write a constructor with an Enum as the parameter and UnityDependencyResolver cannot initialize this constructor.

I guess the Enum parameter is the cause of the problem. I tried to search using the keyword "UnityDependencyResolver can't resolve Enum", but couldn't find any explanation.

Can someone give me accurate information or a satisfactory explanation? Look forward to the help.


Solution

  • It's been so long ago since I wrote Dependency Injection in .NET that I no longer really remember how this works, but according to it:

    Conceptually, it doesn’t always make much sense to register a string or number as a component in a container. However, with Unity this is at least possible.

    Consider, as an example, this constructor:

    public ChiliConCarne(Spiciness spiciness)
    

    In this example, Spiciness is an enum:

    public enum Spiciness
    {
        Mild = 0,
        Medium,
        Hot
    }
    

    [...]

    If you want all consumers of Spiciness to use the same value, you can register Spiciness and ChiliConCarne independently of each other:

    container.RegisterInstance(Spiciness.Medium);
    container.RegisterType<ICourse, ChiliConCarne>();
    

    When you subsequently resolve ChiliConCarne it will have a Medium Spiciness, as will all other components with a DEPENDENCY on Spiciness.

    Have you registered the enum value with the container?