Autofac小例子
AutoFac是.net平台下的IOC容器产品。今天学习一下它的使用方法。
1.最简单的使用。
public interface ITestDao { string SayHello(); } public class TestDao : ITestDao { public string SayHello() { return "hello world!"; } } var builder = new ContainerBuilder(); builder.RegisterType<TestDao>().As<ITestDao>(); IContainer container = builder.Build(); var tdao = container.Resolve<ITestDao>(); string saystr = tdao.SayHello();
builder.RegisterType<TestDao>().As<ITestDao>();注册TestDao是ITestDao的实现。
然后下面进行调用就行。
2.跟mvc一起使用
public interface ITestDao { string SayHello(); } public class TestDao : ITestDao { public string SayHello() { return "hello world!"; } } public class HomeController : Controller { private ITestDao _testDao; public HomeController(ITestDao testDao) { this._testDao = testDao; } public ActionResult Index() { string saystr = _testDao.SayHello(); return View(); } }
在Global.asax里需要添加几行代码
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { //依赖注入 var builder = new ContainerBuilder(); SetupResolveRules(builder); builder.RegisterControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } private void SetupResolveRules(ContainerBuilder builder) { builder.RegisterType<TestDao>().As<ITestDao>(); } }
3.将注册代码放进配置文件。
public interface ITestDao { string SayHello(); } public class TestDao : ITestDao { public string SayHello() { return "hello world!"; } } public class HomeController : Controller { private ITestDao _testDao; public HomeController(ITestDao testDao) { this._testDao = testDao; } public ActionResult Index() { string saystr = _testDao.SayHello(); return View(); } }
在Global.asax里需要添加几行代码
protected void Application_Start() { //依赖注入 var builder = new ContainerBuilder(); builder.RegisterModule(new ConfigurationSettingsReader("autofac")); builder.RegisterControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
在Web.config添加配置文件
<configSections> <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" /> </configSections> <autofac defaultAssembly="MvcApplication11"> <components> <component type="MvcApplication11.Models.TestDao" service="MvcApplication11.Models.ITestDao" /> </components> </autofac>
4.系统自动注册,省略掉手工的配置和xml文件配置。(2014-07-16补充)
写一个基础接口,让你所有的接口都实现此接口,此接口起到的作用仅仅是个标识作用。
public interface IAutofac//标识接口 { } public interface ITestDao : IAutofac { string SayHello(); } public class TestDao : ITestDao { public string SayHello() { return "hello world!"; } } public class HomeController : Controller { private ITestDao _testDao; public HomeController(ITestDao testDao) { this._testDao = testDao; } public ActionResult Index() { string saystr = _testDao.SayHello(); return View(); } }
然后更改Global.asax里面的代码,AppDomain.CurrentDomain.GetAssemblies()获取当前程序域里所有的程序集,下面让RegisterAssemblyTypes自动注册所有继承了IAutofac的接口。
protected void Application_Start() { //依赖注入 var builder = new ContainerBuilder(); //builder.RegisterModule(new ConfigurationSettingsReader("autofac")); var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList(); builder.RegisterAssemblyTypes(assemblys.ToArray()) .Where(e => typeof(IAutofac).IsAssignableFrom(e) && e != typeof(IAutofac)) .AsImplementedInterfaces() .InstancePerLifetimeScope(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端