var container = new MyContainer();
container.RegisterType<ILanguage, Chinese>();
//使用别名注册
container.RegisterType<ILanguage, Englisth>("english");
var language = container.Resolve<ILanguage>();
var english = container.Resolve<ILanguage>("english");
Console.WriteLine(language.GetContent());
Console.WriteLine(english.GetContent());
Console.Read();
public interface ILanguage
{
public string GetContent();
}
public class Chinese:ILanguage
{
public string GetContent()
{
return "学习中文";
}
}
public class Englisth : ILanguage
{
public string GetContent()
{
return "Learning English";
}
}
public interface IMyContainer
{
/// <summary>
/// 注册单一类型
/// </summary>
/// <typeparam name="TType"></typeparam>
void RegisterType<TType>();
/// <summary>
/// 注册单一类型
/// </summary>
/// <typeparam name="TType"></typeparam>
/// <param name="name"></param>
void RegisterType<TType>(string name);
/// <summary>
/// 映射关系
/// </summary>
/// <typeparam name="TType"></typeparam>
/// <typeparam name="TImplementation"></typeparam>
void RegisterType<TType, TImplementation>();
void RegisterType<TType, TImplementation>(string name);
/// <summary>
/// 解析类型
/// </summary>
/// <typeparam name="TType"></typeparam>
/// <returns></returns>
TType Resolve<TType>();
/// <summary>
/// 解析类型
/// </summary>
/// <typeparam name="TType"></typeparam>
/// <param name="name"></param>
/// <returns></returns>
TType Resolve<TType>(string name);
}
public class MyContainer:IMyContainer
{
private static readonly Dictionary<string, object> ContainerDictionary = new Dictionary<string, object>();
public void RegisterType<TType>()
=> RegisterType<TType, TType>(null);
public void RegisterType<TType, TImplementation>()
=> RegisterType<TType, TImplementation>(null);
public void RegisterType<TType>(string name) =>
RegisterType<TType, TType>(null);
public void RegisterType<TType, TImplementation>(string name)
{
string key = typeof(TType).FullName;
if (!string.IsNullOrEmpty(name)) key = name;
if (ContainerDictionary.ContainsKey(key))
ContainerDictionary[key] = typeof(TImplementation); //如果存在采取覆盖形式
else
ContainerDictionary.Add(key, typeof(TImplementation));//将传进来的泛
}
public TType Resolve<TType>()
=>
Resolve<TType>(null);
public TType Resolve<TType>(string name)
{
//解析泛型Type获取key
var key = typeof(TType).FullName;
if (!string.IsNullOrWhiteSpace(name)) key = name;
// 根据key从容器中获取实现类
var type = (Type)ContainerDictionary[key];
//创建对象
return (TType)Activator.CreateInstance(type);
}
}
标签:string,RegisterType,void,key,手写,IOC,public,name From: https://www.cnblogs.com/wugh8726254/p/17429737.html