经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
autofac JSON文件配置
来源:cnblogs  作者:JeffreyGoogle  时间:2018/10/25 9:37:16  对本文有异议

 

autofac是比较简单易用的IOC容器。下面我们展示如何通过json配置文件,来进行控制反转。

需要用到以下程序集。可以通过nugget分别安装

Microsoft.Extensions.Configuration.dll

Microsoft.Extensions.Configuration.Json

 Autofac.Configuration.dll

 

注意,项目目标框架最好设置为.NET Framework 4.6.1及以上。因为Microsoft.Extensions.Configuration.dll,依赖.NETStandard2.0 

 下表列出了 .NET Standard 的所有版本及其支持的平台

 

AutofacExt帮助类

  1. using Autofac;
  2. using Autofac.Configuration;
  3. using Microsoft.Extensions.Configuration;
  4. namespace autofacConsole
  5. {
  6. public static class AutofacExt
  7. {
  8. private static IContainer _container;
  9. public static void InitAutofac()
  10. {
  11. // Add the configuration to the ConfigurationBuilder.
  12. var config = new ConfigurationBuilder();
  13. config.AddJsonFile("autofac.json");
  14. // Register the ConfigurationModule with Autofac.
  15. var module = new ConfigurationModule(config.Build());
  16. var builder = new ContainerBuilder();
  17. builder.RegisterModule(module);
  18. // Set the dependency resolver to be Autofac.
  19. _container = builder.Build();
  20. }
  21. /// <summary>
  22. /// 从容器中获取对象
  23. /// </summary>
  24. /// <typeparam name="T"></typeparam>
  25. public static T GetFromFac<T>()
  26. {
  27. return _container.Resolve<T>();
  28. // return (T)DependencyResolver.Current.GetService(typeof(T));
  29. }
  30. public static T GetFromFac<T>(string name)
  31. {
  32. return _container.ResolveNamed<T>(name);
  33. }
  34. }
  35. }

 客户端调用

  1. public interface IOutput
  2. {
  3. void Write(string content);
  4. }
  5. public class ConsoleOutput : IOutput
  6. {
  7. public void Write(string content)
  8. {
  9. Console.WriteLine(content);
  10. }
  11. }
  12. class Program
  13. {
  14. static void Main(string[] args)
  15. {
  16. AutofacExt.InitAutofac();
  17. var writer =AutofacExt.GetFromFac<IOutput>();
  18. writer.WriteDate();
  19. Console.ReadKey();
  20. }
  21. }

 

 json配置文件配置

Autofac.json 

  1. {
  2. "defaultAssembly": "autofacConsole",
  3. "components": [
  4. {
  5. "type": "autofacConsole.ConsoleOutput, autofacConsole",
  6. "services": [
  7. {
  8. "type": "autofacConsole.IOutput,autofacConsole"
  9. }
  10. ],
  11. "instanceScope": "single-instance",
  12. "injectProperties": true
  13. }
  14. ]
  15. }

设置为如果较新则复制

 

参考资料:

https://github.com/autofac/Autofac

https://autofac.readthedocs.io/en/latest/getting-started/index.html

https://autofac.readthedocs.io/en/latest/configuration/xml.html

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号