tartup.cs文件进行注入工作:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TianYa.DotNetShare.SharpCore.Extensions;
namespace TianYa.DotNetShare.CoreMvcDemo
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//DI依赖注入,批量注入指定的程序集
services.RegisterTianYaSharpService(new string[] { "TianYa.DotNetShare.Repository", "TianYa.DotNetShare.Service" });
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
其中用来实现批量依赖注入的只要一句话就搞定了,如下所示:
//DI依赖注入,批量注入指定的程序集
services.RegisterTianYaSharpService(new string[] { "TianYa.DotNetShare.Repository", "TianYa.DotNetShare.Service" });
Sharp核心类库在底层实现了批量注入的逻辑,程序集的注入必须按照先后顺序进行,先进行仓储层注入然后再进行服务层注入。
接下来我们来看看控制器里面怎么弄:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TianYa.DotNetShare.CoreMvcDemo.Models;
using TianYa.DotNetShare.Service;
using TianYa.DotNetShare.Repository;
namespace TianYa.DotNetShare.CoreMvcDemo.Controllers
{
public class HomeController : Controller
{
/// <summary>
/// 定义仓储层学生抽象类对象
/// </summary>
protected IStudentRepository StuRepository;
/// <summary>
/// 定义服务层学生抽象类对象
/// </summary>
protected IStudentService StuService;
/// <summary>
/// 通过构造函数进行注入
/// 注意:参数是抽象类,而非实现类,因为已经在Startup.cs中将实现类映射给了抽象类
/// </summary>
/// <param name="stuRepository">仓储层学生抽象类对象</param>
/// <param name="stuService">服务层学生抽象类对象</param>
public HomeController(IStudentRepository stuRepository, IStudentService stuService)
{
this.StuRepository = stuRepository;
this.StuService = stuService;
}
public IActionResult Index()
{
var stu1 = StuRepository.GetStuInfo(