Example 1-- dependency injection constructor injection

Introduction: Three examples are injected written in C #, and follow the blog post the order to the database example

Constructor injection: As the name suggests, is to use a constructor implemented in the form of injection

And on the blog post here the difference is more than one interface, Order injected into the interface, rather than specific classes.

SqlServerDal, Access categories:

Database implementation of the interface, with the added functionality of orders

using System;


namespace Ioc2
{
    class SqlServerDal:IDataAccess
    {
        public void Add()
        {
            Console.WriteLine("在sqlserver数据库中添加一条订单");
        }
    }
}

namespace Ioc2
{
     class Access:IDataAccess
     {
        public void Add()
        {
            Console.WriteLine("在access数据库中添加一条订单");
        }
     }
}

Order categories:

The database abstract behavior (Interface) function constructed injection

namespace Ioc2
{
    class Order
    {
        private IDataAccess _ida;
        public Order(IDataAccess ida)
        {
            this._ida = ida;
        }

        public void Add()
        {
            _ida.Add();
        }

    }
}

Database Interface IDataAccess:

Interface is an abstract class actions, the database is used to add data, the data can be added not only sqlserver database, so we will Add () this behavior abstracted, can be added as long as the order of the database class can be injected.

namespace Ioc2
{
    interface IDataAccess
    {
        void Add();
    }
}

Client:

Which database with which to instantiate and written to the Order class as a parameter

namespace Ioc2
{
    class Program
    {
        static void Main(string[] args)
        {
            //这里用的是sqlserver数据库
            //如果要改为其他数据库,添加其他数据库的类并在此实例化即可
            SqlServerDal dal = new SqlServerDal();
            //Access access=new Access();
            Order order = new Order(dal);
            //调用Add()方法,添加订单
            order.Add();
        }
    }
}

 

 

 

 

Published 245 original articles · won praise 23 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_41026669/article/details/104878807