using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Demo.BLL { #region 调用 public class Demo { public void Test() { ITimeProvider timeProvider = (new Assembler()).Create<ITimeProvider>(); Client _client = new Client(); _client.timeProvider = timeProvider; Console.WriteLine(_client.GetYear()); Console.WriteLine(_client.GetDatetime()); //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(); } } #endregion #region 属性接口 public interface ITimeProvider { DateTime CurrentDate { get; } string CurrentYear { get; } } public class TimeProvider : ITimeProvider { public DateTime CurrentDate { get { return DateTime.Now; } } public string CurrentYear { get { return DateTime.Now.Year.ToString(); } } } public class Assembler { private static Dictionary<Type, Type> dictionary = new Dictionary<Type, Type>(); public Assembler() { dictionary.Add(typeof(ITimeProvider), typeof(TimeProvider)); } public object Create(Type type) { if (type == null || !dictionary.ContainsKey(type)) throw new NullReferenceException(); Type targetType = dictionary[type]; return Activator.CreateInstance(targetType); } public T Create<T>() { return (T)Create(typeof(T)); } } public class Client { public ITimeProvider timeProvider { get; set; } public string GetYear() { return timeProvider.CurrentYear.ToString(); } public string GetDatetime() { return timeProvider.CurrentDate.ToString(); } } #endregion #region 方法接口 internal interface IServiceClass { string ServiceInfo(); } internal class ServiceClassA : IServiceClass { public string ServiceInfo() { return "我是ServceClassA"; } } 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()); } } #endregion }View Code