Autofac 4 netcore with config demo

Autofac 4+以上和之前的配置不同的,最近在NetCore中作項目,獲得實例時折騰了一番。javascript

使用場景,用autofac實例化數據庫類型,避免一個個的去newhtml

json配置文件:java

<?xml version="1.0" encoding="utf-8" ?>
<autofac defaultAssembly="Data.Orm.Dapper">
  <components name="Chloe">
    <key>ChloeMssqlKey</key>
    <type>Data.Orm.Chloe.SqlServerDatabase,Data.Orm.Chloe</type>
    <services name="IDatabase2" type="Data.DbFactory.IDatabase,Data.DbFactory" />
    <injectProperties>true</injectProperties>
    <parameters>
      <conn>4</conn>
    </parameters>
  </components>
  <components name="DapperMssql">
    <key>DapperMssqlKey</key>
    <type>Data.Orm.Dapper.SqlServerDatabase, Data.Orm.Dapper</type>
    <services name="IDatabase" type="Data.DbFactory.IDatabase,Data.DbFactory" />
    <injectProperties>true</injectProperties>
    <parameters>
      <conn>4</conn>
    </parameters>
  </components>
</autofac>

  註冊:sql

var config = new ConfigurationBuilder();
            string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"Configs\autofac.xml");
            //config.AddJsonFile(path);//Microsoft.Extensions.Configuration.json.dll
            config.AddXmlFile(path);//Microsoft.Extensions.Configuration.xml.dll

            // Register the ConfigurationModule with Autofac.
            var module = new ConfigurationModule(config.Build());
            var builder = new ContainerBuilder();
            builder.RegisterModule(module);
            container = builder.Build();

獲取:數據庫

/// <summary>
        /// 獲取對象實例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceName">數據庫類型</param>
        /// <param name="param">數據庫鏈接串等參數</param>
        /// <returns></returns>
        public static T GetDbInstance<T>(string serviceName, params Parameter[] param)
        {
            if (container != null)
            {
                var serviceList = container.Resolve<IEnumerable<T>>(param);//http://www.bkjia.com/Asp_Netjc/1315802.html
                foreach (var service in serviceList)
                {
                    if (service.ToString().ToLower().Equals(serviceName.ToLower()))
                    {
                        return service;
                    }
                }
            }
            return default(T);
        }
container.Resolve<IEnumerable<T>>(param)這個地方折騰了很久,開始覺得像之前同樣註冊多個,能夠根據ID或name獲取,實際上一直未獲取到(這裏一直不知道緣由,一直提示未註冊,但願高人能夠指點下)

container.Resolve<Service>(param)
container.ResolveNamed<Service>()
container.ResolveKeyed<Service>()json

若是去掉IEnumerable,則只能獲得最後一個組件。

另外,參數說明:

Autofac提供了集中參數匹配類別:app

  • NamedParameter - 直接經過名稱匹配目標參數
  • TypedParameter - 經過類型來匹配目標參數
  • ResolvedParameter - 靈活的參數匹配

NamedParameter 和 TypedParameter只支持常量。ui

ResolvedParameter 可以使用從容器中動態解析的值做爲參數, 例如經過名字解析出的服務。spa

好比數據庫鏈接:能夠在xml配置一個默認的,也能夠動態實例化時傳入進去:code

Data.DbFactory.IDatabase database  = BaseUtility.Ioc.AutofacHelper.GetDbInstance<Data.DbFactory.IDatabase>("Data.Orm.Chloe.SqlServerDatabase",
                new ResolvedParameter(
           (pi, ctx) => pi.ParameterType == typeof(string) && pi.Name == "conn",
           (pi, ctx) => "Data Source = .;Initial Catalog = Opencsharp.Net;Integrated Security = SSPI;")
                );//按實際傳入的實例化
            Data.DbFactory.IDatabase database2 = BaseUtility.Ioc.AutofacHelper.GetDbInstance<Data.DbFactory.IDatabase>("Data.Orm.Chloe.SqlServerDatabase");//取默認的
相關文章
相關標籤/搜索