• AutoFac使用


    AutoFac 依赖注入框架简单使用与封装

    学习园子内的autofac使用,顺带封装了下。

    简单使用:

    1 public class SqlServerDal:IDal
    2     {
    3         public void Insert(string str)
    4         {
    5             Console.WriteLine("sqlserver");
    6         }
    7     }
    View Code
    1 public class RedisDal:IDal
    2     {
    3        public void Insert(string str)
    4        {
    5            Console.WriteLine("Redis");
    6        }
    7     }
    View Code
    1 public interface IDal
    2    {
    3        void Insert(string str);
    4    }
    View Code

    上面定义完类和接口,通过autofac来实现注入,实现松耦合。

    1             var builder = new ContainerBuilder();
    2             builder.RegisterType<DbConfig>();
    3             builder.RegisterType<SqlServerDal>().As<IDal>();
    4             using (var container = builder.Build())
    5             {
    6                 var config = container.Resolve<DbConfig>();//解析实例
    7                 config.Insert("sql");
    8             }
    View Code

    封装之后:

     1  public  class Container
     2   {
     3       private  IContainer _container;
     4       public  Container(params IModule[] modules)
     5       {
     6           var builder = CreateBuilder(modules);
     7          _container= builder.Build();
     8       }
     9       public  ContainerBuilder CreateBuilder(params IModule[] modules)
    10       {
    11           var builder = new ContainerBuilder();
    12           foreach (IModule module in modules)
    13           {
    14               builder.RegisterModule(module);
    15           }
    16           return builder;
    17       }
    18 
    19       public  T Create<T>()
    20       {
    21           return _container.Resolve<T>();
    22       }
    23     }
    View Code

    这里写下如何使用:

    继承于module的类中写上要注册的组件名称。

    1 public class Config:Module
    2     {
    3        protected override void Load(ContainerBuilder builder)
    4        {
    5            base.Load(builder);
    6            builder.RegisterType<SqlServerDal>().As<IDal>();
    7            builder.RegisterType<DbConfig>();
    8        }
    9     }
    View Code

    最后使用:

    1   Container container = new Container(new Config());
    2             var dal= container.Create<DbConfig>();
    3             dal.Insert("sql");
    View Code
  • 相关阅读:
    Codeforces 1184C1. Heidi and the Turing Test (Easy)题解
    CodeChef Chef and Digit Jumps 题解
    CodeChef Squirrel and chestnut 题解
    Atcoder Beginner Contest 082 C
    Atcoder Beginner Contest 081 C
    Atcoder Beginner Contest 080 C
    Atcoder Beginner Contest 079 C
    Atcoder Beginner Contest 078 C
    Topcoder 10524(SRM451 Div.1 C) BrickPuzzle题解
    广义表是非线性结构
  • 原文地址:https://www.cnblogs.com/wuyuetian/p/4559247.html
Copyright © 2020-2023  润新知