/// <summary>
/// 定义一个容器
/// </summary>
public static IContainer container { get; set; }
/// <summary>
/// 获取dal实例化对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Resolve<T>()
{
try
{
if (container == null)
{
Initialise();
}
}
catch (Exception ex)
{
throw new System.Exception("IOC实例化出错!" + ex.Message);
}
return container.Resolve<T>();
}
/// <summary>
/// 初始化容器
/// </summary>
public static void Initialise()
{
var builder = new ContainerBuilder();
builder.RegisterType<CommodityDAL>().As<ICommodityDAL>().InstancePerLifetimeScope();
builder.RegisterType<StockDAL>().As<IStockDAL>().InstancePerLifetimeScope();
container = builder.Build();
}
调用
private ICommodityDAL _commodityDAL = Container.Resolve<ICommodityDAL>();