最后我们实现仓储接口和方法,即可完成校验流程。
/// <summary> /// 金焰的世界 /// 2018-12-18 /// 用户仓储接口 /// </summary> public interface ICzarUsersRepository { /// <summary> /// 根据账号密码获取用户实体 /// </summary> /// <param>账号</param> /// <param>密码</param> /// <returns></returns> CzarUsers FindUserByuAccount(string uaccount, string upassword); /// <summary> /// 根据用户主键获取用户实体 /// </summary> /// <param>用户标识</param> /// <returns></returns> CzarUsers FindUserByUid(string sub); } /// <summary> /// 金焰的世界 /// 2018-12-18 /// 用户实体基于SQLSERVER的实现 /// </summary> public class CzarUsersRepository : ICzarUsersRepository { private readonly string DbConn = ""; public CzarUsersRepository(IOptions<CzarConfig> czarConfig) { DbConn = czarConfig.Value.DbConnectionStrings; } /// <summary> /// 根据账号密码获取用户实体 /// </summary> /// <param>账号</param> /// <param>密码</param> /// <returns></returns> public CzarUsers FindUserByuAccount(string uaccount, string upassword) { using (var connection = new SqlConnection(DbConn)) { string sql = @"SELECT * from CzarUsers where uAccount=@uaccount and uPassword=upassword and uStatus=1"; var result = connection.QueryFirstOrDefault<CzarUsers>(sql, new { uaccount, upassword = SecretHelper.ToMD5(upassword) }); return result; } } /// <summary> /// 根据用户主键获取用户实体 /// </summary> /// <param>用户标识</param> /// <returns></returns> public CzarUsers FindUserByUid(string sub) { using (var connection = new SqlConnection(DbConn)) { string sql = @"SELECT * from CzarUsers where uid=@uid"; var result = connection.QueryFirstOrDefault<CzarUsers>(sql, new { uid=sub }); return result; } } }现在万事俱备,之前注入和插入测试用户数据进行测试了,为了方便注入,我们采用autofac程序集注册。
/// <summary> /// 金焰的世界 /// 2018-12-18 /// 使用程序集注册 /// </summary> public class CzarModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { //注册Repository程序集 builder.RegisterAssemblyTypes(typeof(CzarUsersRepository).GetTypeInfo().Assembly).AsImplementedInterfaces().InstancePerLifetimeScope(); //注册Services程序集 builder.RegisterAssemblyTypes(typeof(CzarUsersServices).GetTypeInfo().Assembly).AsImplementedInterfaces().InstancePerLifetimeScope(); } }然后需要修改ConfigureServices代码如下,就完成了仓储和服务层的注入。
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddSingleton(Configuration); services.Configure<CzarConfig>(Configuration.GetSection("CzarConfig")); services.AddIdentityServer(option=> { option.PublicOrigin = Configuration["CzarConfig:PublicOrigin"]; }) .AddDeveloperSigningCredential() .AddDapperStore(option => { option.DbConnectionStrings = Configuration["CzarConfig:DbConnectionStrings"]; }) .AddResourceOwnerValidator<CzarResourceOwnerPasswordValidator>() ; // .UseMySql(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //使用Autofac进行注入 var container = new ContainerBuilder(); container.RegisterModule(new CzarModule()); container.Populate(services); return new AutofacServiceProvider(container.Build()); }