public class config
{
public static IContainer iocContainer;
public static void configInit()
{
var build = new ContainerBuilder();
//build.RegisterType<DAL>();
//build.RegisterInstance(new DAL());
//build.RegisterGeneric(typeof(DAL));
//build.RegisterType<DAL>().InstancePerDependency(); //每次变
build.RegisterType<DAL>().InstancePerLifetimeScope(); //程序生命周期内不变, 这个线程或生命周期要自己设置管理,不是自动识别你程序里的线程。
//build.RegisterType<DAL>().SingleInstance(); //单例
//build.RegisterType<DAL>().InstancePerOwned();
iocContainer = build.Build();
}
}
ILifetimeScope scope;
private void button1_Click(object sender, EventArgs e)
{
//var dal = config.iocContainer.Resolve<DAL>();
if (scope == null)
scope = config.iocContainer.BeginLifetimeScope();
{
var dal = scope.Resolve<DAL>();
Console.WriteLine(dal.getdata("fc101") + "\r\n" + dal.GetHashCode().ToString() + ": " + Thread.CurrentThread.ManagedThreadId.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
//var dal = config.iocContainer.Resolve<DAL>();
//using (var scope = config.iocContainer.BeginLifetimeScope())
{
var dal = scope.Resolve<DAL>();
Console.WriteLine(dal.getdata("fc102") + "\r\n" + dal.GetHashCode().ToString() + ": " + Thread.CurrentThread.ManagedThreadId.ToString());
}
}
private void button3_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}
Task.Run(() => {
//var dal = config.iocContainer.Resolve<DAL>();
using (var scope = config.iocContainer.BeginLifetimeScope())
{
var dal = scope.Resolve<DAL>();
Console.WriteLine(dal.getdata("fc103") + "\r\n" + dal.GetHashCode().ToString() + ": " + Thread.CurrentThread.ManagedThreadId.ToString());
}
});