public static class AutofacExt { static ContainerBuilder containerBuilder; static IContainer _container; public static IContainer container { get { if (_container == null) { _container = containerBuilder.Build(); } return _container; } } public static void InitAutofact() { containerBuilder = new ContainerBuilder(); var config = new ConfigurationBuilder(); config.AddXmlFile("Autofac.config"); var module = new ConfigurationModule(config.Build()); containerBuilder.RegisterModule(module); _container = containerBuilder.Build(); } public static T GetObject<T>() { return container.Resolve<T>(); } }
这是我 写的 autofac 注册 的一个帮助类,
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="Default" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/> </configSections> <Default> <components> <componet type="ImplementBLL.CustomersBLL,ImplementBLL" service="InterfaceBLL.ICustomersBLL,InterfaceBLL" /> </components> </Default> </configuration>
这是我的配置文件
public ActionResult Index() { AutofacExt.InitAutofact(); var cusBLL = AutofacExt.GetObject<ICustomersBLL>(); var customers = cusBLL.GetCustomers(); return View(customers); }
测试调用代码
为什么依然 提示 ICustomers 是未注册类型呢