Autofac生命周期 和各种注入 本文共有2620个字,关键词: //builder.RegisterType<TestA>().As<ITestA>().InstancePerDependency();//瞬态 //builder.RegisterType<TestB>().As<ITestB>().SingleInstance();//单例 //builder.RegisterType<TestC>().As<ITestC>().InstancePerLifetimeScope();//作用域,应用域 //builder.RegisterType<TestD>().As<ITestD>().InstancePerMatchingLifetimeScope("TEST");指定作用域,指定应用域ContainerBuilder containerBuilder = new ContainerBuilder(); //注册抽像与具体类 containerBuilder.RegisterType<MainClass>().As<IMainClass>(); IContainer container = containerBuilder.Build(); IMainClass mainClass = container.Resolve<IMainClass>(); //注册具体实例 containerBuilder.RegisterInstance(new MainClass(new ChildClass())); IContainer container = containerBuilder.Build(); IMainClass mainClass = container.Resolve<IMainClass>(); //业务逻辑注入 containerBuilder.Register<IMainClass>( context => { IChildClass childClass = context.Resolve<IChildClass>(); IMainClass mainClass1 = new MainClass(childClass); return mainClass1; }); //泛型注入 containerBuilder.RegisterGeneric(typeof(List<>)).As(typeof(IList<>)); IContainer container = containerBuilder.Build(); IList<MainClass> mainClasses = container.Resolve<IList<MainClass>>(); //count= 0 containerBuilder.RegisterGeneric(typeof(List<>)).As(typeof(IList<>)); containerBuilder.RegisterType<MainClass>().As<IMainClass>(); IContainer container = containerBuilder.Build(); IList<IMainClass> mainClasses = container.Resolve<IList<IMainClass>>(); //count= 1 //程序集注入 Assembly interfaceAssbly = Assembly.LoadFrom("MBS.IConsoleApp.dll"); Assembly servicesAssbly = Assembly.LoadFrom("MBS.ConsoleApp.dll"); containerBuilder.RegisterAssemblyOpenGenericTypes(interfaceAssbly, servicesAssbly).AsImplementedInterfaces(); IContainer container = containerBuilder.Build(); IMainClass mainClass = container.Resolve<IMainClass>(); 「一键投喂 软糖/蛋糕/布丁/牛奶/冰阔乐!」 赞赏 × 梦白沙 (๑>ڡ<)☆谢谢老板~ 1元 2元 5元 10元 50元 任意金额 2元 使用微信扫描二维码完成支付 版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。 dotNET 2022-05-17 评论 342 次浏览