class Program { static void Main(string[] args) { IContainer container = Init(); Go(container); Console.WriteLine("========================"); ISchool a = container.Resolve<ISchool>(); a.FangXue(); Console.ReadKey(); } static IContainer Init() { ContainerBuilder builder = new ContainerBuilder(); Assembly asm = Assembly.Load(Assembly.GetExecutingAssembly().GetName().Name); builder.RegisterAssemblyTypes(asm).AsImplementedInterfaces().PropertiesAutowired().SingleInstance(); //SingleInstance()单例,共享同一个对象,PropertiesAutowired()属性自动注入 IContainer container = builder.Build(); return container; } static void Go(IContainer container) { IDogBLL schoolBll = container.Resolve<IDogBLL>(); schoolBll.Bark(); IDogBLL schoolBll2 = container.Resolve<IDogBLL>(); Console.WriteLine(schoolBll.Equals(schoolBll2)); } } public interface IDogBLL { void Bark(); } public class DogBLL : IDogBLL { public void Bark() { Console.WriteLine("汪汪汪"); } } public interface ISchool { void FangXue(); } public class School : ISchool { public IDogBLL dogBll { get; set; } public void FangXue() { dogBll.Bark(); Console.WriteLine("放学了"); } }
Autofac.Mvc
private void AutoFacMvc() { //using Autofac.Integration.Mvc; ContainerBuilder builder = new ContainerBuilder(); // 把当前的 程序集中的 Controller 都注册 builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired(); // 不要忘了.PropertiesAutowired() Assembly asm = Assembly.Load("TestService"); //获取所有相关类库的程序集 builder.RegisterAssemblyTypes(asm).Where(e => !e.IsAbstract).AsImplementedInterfaces().PropertiesAutowired(); // 把当前的 程序集中的 所有类 都注册 builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).PropertiesAutowired(); Autofac.IContainer container = builder.Build(); //注册系统级别的 DependencyResolver, //这样当 MVC框架创建Controller等对象的时候都是管Autofac要对象。 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //!!! }
Autofac.Mvc单独注册
var test = DependencyResolver.Current.GetService<TestHelper>(); var res = test.GetDateTime();
不在Mvc线程里单独注册
var container = AutofacDependencyResolver.Current.ApplicationContainer; using (container.BeginLifetimeScope()) { var citySvc = container.Resolve<ICityService>(); }