ASP.NETCore dependency injection using AutoFac

 

Implementation code

1, the new interface class: IRepository.cs, those specifications have respective operating class, easy management.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace CMS.Entity.Interfaces
{
    public  interface IRepository<T> where T:class
    {
        ///  <Summary> 
        /// Add
         ///  </ Summary> 
        ///  <param name = "Entity"> Entity Object </ param> 
        void the Add (T Entity);
         ///  <Summary> 
        /// update
         ///  </ Summary> 
        ///  <param name = "entity"> entity Object </ param> 
        void the update (T entity);
         ///  <Summary> 
        /// remove
         ///  </ Summary> 
        / //  <param name = "entity"> entity Object </ param> 
        void the Delete (T entity);
        /// <summary>
        ///Remove
         ///  </ Summary> 
        ///  <param name = "WHERE"> conditions (lambda expression) </ param> 
        void the Delete (the Expression <Func <T, BOOL >> WHERE );
         ///  <Summary> 
        /// Gets an object according ID
         ///  </ Summary> 
        ///  <param name = "Id"> primary key ID </ param> 
        ///  <Returns> Object </ Returns> 
        T GetById ( Long Id);
         ///  <Summary> 
        /// ID Gets an object according
         ///  </ Summary> 
        ///  <param name="Id">主键ID</ param> 
        ///  <Returns> Object </ Returns> 
        T GetById ( String Id);
         ///  <Summary> 
        /// Gets an object according to the conditions
         ///  </ Summary> 
        ///  <param name = "where"> conditions (lambda expression) </ param> 
        ///  <Returns> Object </ Returns> 
        T the Get (the expression <Func <T, BOOL >> WHERE );
         ///  <Summary> 
        /// Get All data
         ///  </ Summary> 
        ///  <Returns> All data </ returns>
        IQueryable<T>GetAll ();
         ///  <Summary> 
        /// Get Data under the conditions
         ///  </ Summary> 
        ///  <param name = "WHERE"> conditions (lambda expression) </ param> 
        ///  <Returns > data </ Returns> 
        IQueryable <T> GetMany (the Expression <Func <T, BOOL >> WHERE );
         ///  <Summary> 
        /// Get the number of records in accordance with the condition
         ///  </ Summary> 
        ///  <param name = "where"> conditions (lambda expression) </ param> 
        ///  <Returns> </ Returns> 
        int the GetCount (the expression <Func <T,bool>> where);
         ///  <Summary> 
        /// closing agent
         ///  </ Summary> 
        void CloseProxy ();
         ///  <Summary> 
        /// Open Agent
         ///  </ Summary> 
        void OpenProxy ();
         // /  <Summary> 
        /// whether a specified condition element
         ///  </ Summary> 
        ///  <param name = "WHERE"> conditions (lambda expression) </ param> 
        ///  <Returns> </ Returns > 
        BOOL IsHasValue (the Expression <Func <T, BOOL >> WHERE );
    }
}

2, the new class of operation based storage RepositoryBase.cs, attention To achieve correspondence interface IRepositroy

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace CMS.Entity.Interfaces
{
    public abstract class BaseRepository<T>  where T: class
    {
        Private BcmfDBContext DB; // database context

        public BaseRepository(BcmfDBContext _db) {
            db = _db;
        }

        public virtual void Save()
        {
            db.SaveChanges();
        }

        public  virtual  void Add(T entity)
        {
            db.Set<T>().Add(entity);
        }

        public virtual void CloseProxy()
        {
            db.Database.CommitTransaction();
        }

        public virtual void Delete(T entity)
        {
            db.Set<T>().Remove(entity);
        }

        public virtual void Delete(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            var dataList = db.Set<T>().Where(where).AsEnumerable();
            db.Set<T>().RemoveRange(dataList);
        }

        public virtual T Get(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
           return db.Set<T>().FirstOrDefault(where);
        }

        public virtual System.Linq.IQueryable<T> GetAll()
        {
            return db.Set<T>();
        }

        public virtual T GetById(long Id)
        {
            return db.Set<T>().Find(Id);
        }

        public virtual T GetById(string Id)
        {
            return db.Set<T>().Find(Id);
        }

        public virtual int GetCount(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return db.Set<T>().Count(where);
        }

        public virtual System.Linq.IQueryable<T> GetMany(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return db.Set<T>().Where(where);
        }

        public virtual bool IsHasValue(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return db.Set<T>().Any(where);
        }

        public virtual void OpenProxy()
        {
            db.Database.BeginTransaction();
        }

        public virtual void Update(T entity)
        {
            db.Set<T>().Attach(entity);
            db.Entry<T>(entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
        }
    }
}

3, and the new storage class TUserRepository TOperateLogRepository, TUserRepository for operating a user table, TOperateLogRepository for operating a user record table, and User class corresponding to the class OperateLog create their own needs of the project

using System;
using System.Collections.Generic;
using System.Text;
using CMS.Entity.Repository;
using CMS.Entity.Entity;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using CMS.Entity.Interfaces;

namespace CMS.Entity.Repository
{
    public class TUserRepository :BaseRepository<User>,IUserRepository
    {
        public TUserRepository(BcmfDBContext db) : base(db) { }
    }
    public interface IUserRepository : IRepository<User> { }
}
using System;
using System.Collections.Generic;
using System.Text;
using CMS.Entity.Repository;
using CMS.Entity.Entity;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using CMS.Entity.Interfaces;

namespace CMS.Entity.Repository
{

    public class TOperateLogRepository : BaseRepository<OperateLog>, IOperateLogRepository
    {
        public TOperateLogRepository(BcmfDBContext db) : base(db) { }
    }
    public interface IOperateLogRepository : IRepository<OperateLog>
    {
    }
}

 

4, were injected with UserController storage class constructor controller OperateLogController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using CMS.Entity;
using CMS.Entity.Entity;
using Newtonsoft.Json;
using CMS.WebApi.Core;
using Microsoft.EntityFrameworkCore.Query;
using CMS.Entity.Repository;

namespace CMS.WebApi.Controllers
{
    /// <summary>
    /// 用户中心
    /// </summary>
    //[Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    public  class UsersController: ControllerBase
    {

        private readonly IUserRepository userRepository;
        public UsersController(IUserRepository _userRepository)
        {
            userRepository = _userRepository;
        }


        ///  <Summary> 
        /// Gets a list of users
         ///  </ Summary> 
        ///  <Returns> </ Returns> 
        [HttpGet]
         public  String the Get ()
        {
            var userList= userRepository.GetAll().ToList();
            return JsonConvert.SerializeObject(userList);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using CMS.Entity.Repository;
using Newtonsoft.Json;

namespace CMS.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OperateLogController : ControllerBase
    {
        private readonly IOperateLogRepository operateLogRepository;
        public OperateLogController(IOperateLogRepository _operateLogRepository)
        {
            operateLogRepository = _operateLogRepository;
        }

        [HttpGet]
        public string Get()
        {
            var result = operateLogRepository.GetMany(m=>m.ActionLogId<100);
            return JsonConvert.SerializeObject(result);
        }
    }
}

5, after the completion of the operation, when you run the data acquisition system will be an error, it is because not injected into the warehouse class service, then you realize with AutoFac injected into the project and Storage Services

Add a reference Autofac, Auto.Configuration, Autofac.Extensions.DependencyInjection to the project

 

Here posted Nuget program console command:

Install-Package Autofac -Version 4.9.2
Install-Package Autofac.Configuration -Version 4.1.0
Install-Package Autofac.Extensions.DependencyInjection -Version 4.4.0

6, open the project Startup.cs, find ConfigureServices method, instead IServiceProvider void return value, as follows

 //先引用命名空间
using Autofac;
using Autofac.Extensions.DependencyInjection;

public IServiceProvider ConfigureServices(IServiceCollection services) { ... /// / batch injection matching using AutoFac supplied current project default container vessel nozzles var Builder = new new ContainerBuilder (); // injection layer builder.RegisterType entity class repository (typeof (TUserRepository)) As ( typeof (IUserRepository). ) .InstancePerDependency (); // batch injection Repository class   builder.RegisterAssemblyTypes ( typeof (TUserRepository) .assembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces(); builder.Populate(services); var Container = builder.Build (); // ConfigureServices void by the method returns to the IServiceProvider return new new AutofacServiceProvider (Container); }

7, rebuild the publishing project, completed

 

Guess you like

Origin www.cnblogs.com/luckypc/p/11002805.html