.netCoreMVC添加数据仓储

在上一篇关于CodeFirst从零搭建ASP.NETCore2.0中搭建起了完整.netCoreMVC项目,在这一篇中将实现如何注册service服务和Repository数据仓储到web中实现数据的统一处理.

首先新建项目:DotNetCore20.Service:

右键解决方案>新建项目:DotNetCore20.Service

 添加repository

原先计划自己实现一套repository(将在后续计划再写一篇参考:https://github.com/Arch/UnitOfWork实现Repository的文章),但是由于时间原因后来在nuget中找到了更好更全面的解决方案,暂且利用第三方组件实现repository.

nuget搜索:Microsoft.EntityFrameworkCore.UnitOfWork;源代码:https://github.com/Arch/UnitOfWork

安装到DotNetCore20.Service

在DotNetCore20.Service中添加DemoService.cs和对应的接口IDemoService.cs,目录结构如下:

DemoService.cs:

using DotNetCore20.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;

namespace DotNetCore20.Service
{
    public class DemoService : IDemoService
    {
        private readonly IUnitOfWork _unitOfWork;
        public DemoService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<UserExtend> Meth()
        {
            var repo = _unitOfWork.GetRepository<UserExtend>();
            var value = await repo.FindAsync();
            return value;
        }
    }
}

IDemoService:

using DotNetCore20.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;

namespace DotNetCore20.Service
{
    public interface IDemoService
    {
        Task<UserExtend> Meth();
    }
}

 Startup.cs中注册相关服务:

在Startup中的ConfigureServices方法中添加以下行:

//Customer's services
            services.AddUnitOfWork<DotNetCoreDbContext>();//注册数据仓储
            services.AddScoped(typeof(IDemoService), typeof(DemoService));//注册service,为了避免都要在此声明,所以之后会统一注册DotNetCore20.Service下的所有service

 完整Startup如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using DotNetCore20.Web.Data;
using DotNetCore20.Web.Models;
using DotNetCore20.Web.Services;
using DotNetCore20.DAL.DbContext;
using DotNetCore20.Service;

namespace DotNetCore20.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //自定义数据库连接字符串
            services.AddDbContext<DotNetCoreDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

            //Customer's services
            services.AddUnitOfWork<DotNetCoreDbContext>();
            services.AddScoped(typeof(IDemoService), typeof(DemoService));

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
Startup

HomeController:

在Controller的HomeController中的构造函数中添加以下代码:

  public class HomeController : Controller
    {
        private IDemoService _demoService { get; set; }
        public HomeController(IDemoService demoService)
        {
            _demoService = demoService;
        }
}

使用Service

public IActionResult Index()
        {
            _demoService.Meth();

            return View();
        }

在此大功告成,点击即可

原文地址:https://www.cnblogs.com/xiaoliangge/p/7231715.html