小结:c#Constructor构造函数注入
来源:互联网 发布:上海索昂软件 编辑:程序博客网 时间:2024/05/22 01:26
1、创建接口
public interface ITimeProvider { DateTime CurrentDate { get; } string CurrentYear { get; } }
2、继承接口,实现类
public class TimeProvider : ITimeProvider { public DateTime CurrentDate { get { return DateTime.Now; } } public string CurrentYear { get { return DateTime.Now.Year.ToString(); } } }
3、创建注入机制
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)); } }
4、客户端调用
public class Client { private ITimeProvider timeProvider; public Client(ITimeProvider timeProvider) { this.timeProvider = timeProvider; } public string GetYear() { return timeProvider.CurrentYear .ToString(); } public string GetDatetime() { return timeProvider.CurrentDate.ToString(); } }
5、使用实现
ITimeProvider timeProvider = (new Assembler()).Create<ITimeProvider>(); Client clinet = new Client(timeProvider); Console.WriteLine(clinet.GetYear()); Console.WriteLine(clinet.GetDatetime());
0 0
- 小结:c#Constructor构造函数注入
- [C++]default constructor默认构造函数
- 构造函数(constructor)
- 构造函数CONSTRUCTOR
- 构造函数constructor
- 什么是构造函数注入(Constructor Injection)——一个具体的依赖注入例子
- c++: 构造函数(constructor)与各种眼花缭乱的初始化(initialization)
- [C++] Call an overloading constructor within a constructor (C++上构造函数里调用重载构造函数)
- Constructor injection type ambiguities in Spring /使用Spring时,构造函数注入的歧义
- 复制构造函数(copy constructor)
- default constructor(默认构造函数)
- default constructor 的构造函数
- Copy constructor拷贝构造函数
- explicit constructor(显示构造函数)
- 拷贝构造函数 (Copy constructor)
- initCompent()和构造函数(constructor)
- 构造函数语义学---default constructor
- 构造函数语义学----copy constructor
- 11809 - Floating-Point Numbers
- Python 入门 一
- 测试APPEND INSERT是否产生UNDO信息的过程
- Linux下的软件源代码安装
- 字符串-644 Immediate Decodability
- 小结:c#Constructor构造函数注入
- OpenLayers3入门篇-点在线上的运动
- linux 操作系统中检查特定用户上次登录的时间lastlog命令的使用
- poj 1847 最短路 floyd
- android NDK JNI so文件的制作和使用
- C++ OO Programming (1)
- 视频驱动V4L2子系统驱动架构 - 驱动框架
- 猜数游戏(JAVA)
- Android从1.0到 6.0各版本的差别