c# 依赖注入之---setterInjection(转)

 

图3.1 Setter注入示意

定义一个接口:

namespace SetterInjection
{
    internal interface IServiceClass
    {
        string ServiceInfo();
    }
}

定义一个要实现该接口的类A:

internal class ServiceClassA : IServiceClass
    {
        public string ServiceInfo()
        {
            return "我是ServceClassA";
        }
    }

定义一个要实现该接口的类B:

 internal class ServiceClassB : IServiceClass
    {
        public string ServiceInfo()
        {
            return "我是ServceClassB";
        }
    }

 定义一个主体类---注入点:

  internal class ClientClass
    {
        private IServiceClass _serviceImpl;
        public void Set_ServiceImpl(IServiceClass serviceImpl)
        {
            this._serviceImpl = serviceImpl;
        }

        public void ShowInfo()
        {
            Console.WriteLine(_serviceImpl.ServiceInfo());
        }
    }

Main:

   class Program
    {
        static void Main(string[] args)
        {
            //setterInjection
            IServiceClass serviceA = new ServiceClassA();
            IServiceClass serviceB = new ServiceClassB();
            ClientClass client = new ClientClass();

            client.Set_ServiceImpl(serviceA);
            client.ShowInfo();
            client.Set_ServiceImpl(serviceB);
            client.ShowInfo();
            Console.ReadLine();
        }
    }

结果:

 

posted @ 2017-07-15 17:13  幸福安康  阅读(1296)  评论(0编辑  收藏  举报