Way to fill collection with Unity

后端 未结 4 510
粉色の甜心
粉色の甜心 2020-12-09 05:06

I have two example classes

class ClassToResolve
{
    private List _coll;

    public ClassToResolve(List coll)
          


        
4条回答
  •  遥遥无期
    2020-12-09 05:27

    @Steven's answer is perfectly correct, I just want to suggest another way to tackle the issue.

    For the sake of a better and cleaner code, it is worth it to define an interface for all the collection items.

    public interface IMyClass
    {
        void DoSomething();
    }
    
    public abstract class MyClassBase : IMyClass
    {
        abstract void DoSomething();
        // more code for the base class if you need it.
    }
    
    public class MyClassA : MyClassBase
    {
        void virtual DoSomething()
        {
            // implementation here
        }
    }
    
    public class MyClassB : MyClassBase
    {
        void virtual DoSomething()
        {
            // implementation here
        }
    }
    
    public class MyClassC : MyClassBase
    {
        void virtual DoSomething()
        {
            // implementation here
        }
    }
    
    // etc.
    

    Now the registration code for Unity container would be much more easier:

    container.RegisterTypes(
        AllClasses.FromLoadedAssemblies().
            Where(type => typeof(IMyClass).IsAssignableFrom(type)),
        WithMappings.FromAllInterfaces,
        WithName.TypeName,
        WithLifetime.PerResolve);
    
    container.RegisterType, IMyClass[]>();
    

    and the resolve code is the same:

    var allOfMyClasses = container.ResolveAll();
    

    I hope Microsoft add IEnumerable<> support to the next version of Unity so we won't need to register IEnumerable.

提交回复
热议问题