欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

autofac JSON文件配置

程序员文章站 2022-10-17 09:43:18
autofac是比较简单易用的IOC容器。下面我们展示如何通过json配置文件,来进行控制反转。 需要用到以下程序集。可以通过nugget分别安装 Microsoft.Extensions.Configuration.dll Microsoft.Extensions.Configuration.Js ......

 

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 的所有版本及其支持的平台

autofac JSON文件配置

 

autofacext帮助类

using autofac;
using autofac.configuration;
using microsoft.extensions.configuration;

namespace autofacconsole
{
    public static class autofacext
    {
        private static icontainer _container;

        public static void initautofac()
        {

            // add the configuration to the configurationbuilder.
            var config = new configurationbuilder();
            config.addjsonfile("autofac.json");

            // register the configurationmodule with autofac.
            var module = new configurationmodule(config.build());
            var builder = new containerbuilder();
            builder.registermodule(module);


            // set the dependency resolver to be autofac.
            _container = builder.build();

        }

        /// <summary>
        /// 从容器中获取对象
        /// </summary>
        /// <typeparam name="t"></typeparam>
        public static t getfromfac<t>()
        {
            return _container.resolve<t>();
            //   return (t)dependencyresolver.current.getservice(typeof(t));
        }

        public static t getfromfac<t>(string name)
        {
            return _container.resolvenamed<t>(name);
        }
    }
}

 客户端调用

public interface ioutput
    {
        void write(string content);
    }
public class consoleoutput : ioutput { public void write(string content) { console.writeline(content); } } class program { static void main(string[] args) { autofacext.initautofac(); var writer =autofacext.getfromfac<ioutput>(); writer.writedate(); console.readkey(); } }

 

 json配置文件配置

autofac.json 

{
  "defaultassembly": "autofacconsole",
  "components": [
    {
      "type": "autofacconsole.consoleoutput, autofacconsole",
      "services": [
        {
          "type": "autofacconsole.ioutput,autofacconsole"
        }
      ],
      "instancescope": "single-instance",
      "injectproperties": true
    }
  ]
}

设置为如果较新则复制

autofac JSON文件配置

 

参考资料:

https://github.com/autofac/autofac

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

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