C#如何使用某个DI容器动态解析类型?

时间:2018-04-03 15:12:07

标签: c# generics dependency-injection

我有两个参数类型的版本要传递给服务器,我更喜欢保留两个版本并使用unity容器自动解决它(因为它是项目设计的一部分),并且对于大多数两个版本的代码都相同。

在我的配置文件中,我有一个属性Version,可以是1.01.2等值。我想基于此值解析service

这是我的模拟代码以不同的方式来说明我的问题。

enter image description here

using System;

namespace Versions
{
    public interface IService<in T> where T : IObj
    {
        void DoSomething1(T obj);
        void DoSomething2(T obj);
        void DoSomething3(int id);
    }

    public abstract class ServiceBase<T> : IService<T> where T : IObj
    {
        public abstract void DoSomething1(T obj);

        public abstract void DoSomething2(T obj);

        public virtual void DoSomething3(int id)
        {
            Console.WriteLine(id);
        }
    }

    public class Service1<T> : ServiceBase<T> where T : IObj1
    {
        public override void DoSomething1(T obj)
        {
            throw new NotImplementedException();
        }

        public override void DoSomething2(T obj)
        {
            throw new NotImplementedException();
        }
    }

    public class Service2<T> : ServiceBase<T> where T : IObj2
    {
        public override void DoSomething1(T obj)
        {
            throw new NotImplementedException();
        }

        public override void DoSomething2(T obj)
        {
            throw new NotImplementedException();
        }
    }

    public interface IObj
    {
    }

    public interface IObj1 : IObj
    {
        int Id { get; set; }
        string Name { get; set; }
    }

    public interface IObj2 : IObj
    {
        int Id { get; set; }
        string Name { get; set; }
        int Age { get; set; }
        DateTime Dob { get; set; }
    }

    public class Obj1 : IObj1
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Obj2 : IObj2
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime Dob { get; set; }
    }

    public class Program
    {
        // e.g.: v1.0, v1.2
        private static readonly string Version = "v1.0"; // ConfigurationManager.AppSettings["version"];

        static void Main(string[] args)
        {
            SomeContainer container = new SomeContainer();

            var service = container.Resolve(Version);


        }
    }

    public class SomeContainer
    {
        public IService<IObj> Resolve(string version)
        {
            if (version == "v1.0")
            {
                return new Service1<Obj1>();
            }

            if (version == "v1.2")
            {
                return new Service2<Obj2>();
            }

            throw new NotSupportedException("version not supported");
        }
    }
}

0 个答案:

没有答案