VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之autofac JSON文件配置

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帮助类

复制代码
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
    }
  ]
}
复制代码

设置为如果较新则复制

 

参考资料:

https://github.com/autofac/Autofac

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

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

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关教程