public static void Run() { ContainerBuilder cb = new ContainerBuilder(); cb.RegisterType <AccountBll>().As <IAccountBll>(); cb.RegisterType <AccountDal>().As <IAccountDal>(); cb.RegisterType <ConsoleLogger>().As <ILogger>().InstancePerLifetimeScope(); IContainer container = cb.Build(); //using (ILifetimeScope beginLifetimeScope = container.BeginLifetimeScope()) //{ // IAccountBll accountBll = beginLifetimeScope.Resolve<IAccountBll>(); // accountBll.Transfer("yueluo", "newbe", 333); // accountBll.Transfer("yueluo", "newbe", 333); //} /* * IContainer inherits ILifetimeScope, and function BeginLifetimeScope is to begin a new nested scope. * Component instances created via the new scope will be disposed along with it. * So I think this is a better demo. * * Here have three situations: * 1. Single Instance in every lifetime * The ILoggers that AccountBll and AccountDal depend on in every lifetime are the same, * but in different lifetime are different * cb.RegisterType<ConsoleLogger>().As<ILogger>().InstancePerLifetimeScope(); * 2. Single Instance in entire project * The ILoggers that AccountBll and AccountDal depend on in every lifetime are the same, * and in different lifetime are the also the same * cb.RegisterType<ConsoleLogger>().As<ILogger>().SingleInstance(); * 3. Different instance in every step * The ILoggers that AccountBll and AccountDal depend on in every lifetime are different, * and in different lifetime are also different. * cb.RegisterType<ConsoleLogger>().As<ILogger>(); * We can have a try for every situation. The outputs are different: * Maybe the "输出日志" is the same, but the logger hashcode in every function is different. */ using (ILifetimeScope beginLifetimeScope = container.BeginLifetimeScope()) { IAccountBll accountBll = beginLifetimeScope.Resolve <IAccountBll>(); accountBll.Transfer("yueluo", "newbe", 333); } using (ILifetimeScope beginLifetimeScope = container.BeginLifetimeScope()) { IAccountBll accountBll = beginLifetimeScope.Resolve <IAccountBll>(); accountBll.Transfer("yueluo", "newbe", 333); } }