1. 程式人生 > >DotNetCore跨平臺~組件化時代來了

DotNetCore跨平臺~組件化時代來了

depend 文件 manage extension under .get man str http請求

回到目錄

進行dotnetcore之後,各種對象都是基於DI進行生產的,這就有了對象的生命周期一說,早在autofac裏也有相關知識點,這與Microsoft.Extensions.DependencyInjection是完全溫和的,方便大家理解,在講今天的組件化之前,先對DI的三種生命周期進行理解一下:

AddSingleton:單例,進程內它是唯一的

AddTransient:瞬息,在對象在當前環境內,作用域內是唯一的

AddScoped:請求,對象在一個HTTP請求內是唯一的

下面來看今天的組件化的實現,比如我希望對nosql進行封裝,在以後使用它時,直接在代碼startup中進行註冊,或者使用配置文件進行註冊,我們就可以涉及這樣一個擴展方法來實現對IServiceCollection擴展!

    /// <summary>
    /// nosql服務擴展
    /// </summary>
    public static class NoSqlExtensions
    {

        /// <summary>
        /// 使用Redis
        /// </summary>
        /// <param name="services"></param>
        /// <param name="options"></param>
        /// <returns></returns>
public static IServiceCollection UseRedis( this IServiceCollection services, Action<RedisConfig> options = null) { RedisConfig option = new RedisConfig(); options?.Invoke(option); ObjectMapper.MapperTo<RedisConfig>(option, ConfigFileHelper.Get<RedisConfig>());//
優先級裝飾器 services.AddSingleton(option); services.AddSingleton<RedisManager, RedisManager>(); return services; } /// <summary> /// 使用Mongodb /// </summary> /// <param name="services"></param> /// <param name="options"></param> /// <returns></returns> public static IServiceCollection UseMongodb( this IServiceCollection services, Action<MongodbConfig> options = null) { MongodbConfig option = new MongodbConfig(); options?.Invoke(option); ObjectMapper.MapperTo<MongodbConfig>(option, ConfigFileHelper.Get<MongodbConfig>());//優先級裝飾器 services.AddSingleton(option); services.AddSingleton<MongodbManager, MongodbManager>(); return services; } }

在程序中使用時,也是很方便,註意的是,如果配置文件中也配置它了,我們將以配置文件為準,這樣在生產環境裏,你的代碼註入的參數,不用被註釋和刪除!

       #region 服務組件
            services.UseRabbitMQ(o =>
            {
                o.ExchangeName = "Pilipa.AutoCalculate";
                o.MqServerHost = "amqp://192.168.200.214:5672";
            });

            services.UseRedis(o =>
            {
                o.Host = "192.168.200.214:6379";
                o.AuthPassword = "pilipa#2017";
            });

            services.UseDapper(o =>
            {
                o.DbType = 2;
                o.ConnectionString = "test";
            });
            #endregion

感謝各位的閱讀!

我們的框架應該是基於組件化的!

我們的系統應該是基於微服務化的!

我們的部署,應該是基於自動化的!

回到目錄

DotNetCore跨平臺~組件化時代來了