PetaPoco在ASP.NET Core 2.2中使用注入方式访问数据库
.Net Core中一个特别重要的特性就是依赖注入功能,那么我们在使用PetaPoco的时候是否也可以使用依赖注入特性呢?
回答当然是可以的啦。使用方法(两种注入方式)如下
services.AddScoped<IDatabase>( x => { var connectionStrnig = Configuration["ConnectionStrings:MySQL:MvcMySQL"]; var configuration = DatabaseConfiguration.Build().UsingConnectionString(connectionStrnig) .UsingProvider<MariaDbDatabaseProvider>(); return new PetaPocoMvcDBContext(configuration); }); services.AddScoped<IDatabase, PetaPocoMvcDBContext>( (x) => { var connectionStrnig = Configuration["ConnectionStrings:MySQL:MvcMySQL"]; var configuration = DatabaseConfiguration.Build().UsingConnectionString(connectionStrnig) .UsingProvider<MariaDbDatabaseProvider>(); return new PetaPocoMvcDBContext(configuration); });
定义的PetaPocoMvcDBContext类:
namespace PetaPocoEfCoreMvc.DBContext { using System.Data.Common; using PetaPoco; using PetaPoco.Core; public class PetaPocoMvcDBContext:Database { public PetaPocoMvcDBContext(DbConnection connection, IMapper defaultMapper = null) : base(connection, defaultMapper) { } public PetaPocoMvcDBContext(string connectionString, string providerName, IMapper defaultMapper = null) : base(connectionString, providerName, defaultMapper) { } public PetaPocoMvcDBContext(string connectionString, DbProviderFactory factory, IMapper defaultMapper = null) : base(connectionString, factory, defaultMapper) { } public PetaPocoMvcDBContext(string connectionString, IProvider provider, IMapper defaultMapper = null) : base(connectionString, provider, defaultMapper) { } public PetaPocoMvcDBContext(IDatabaseBuildConfiguration configuration) : base(configuration) { } } }
appsetting.json中的数据库连接字符串:
"ConnectionStrings": { "MySQL": { "MvcMySQL": "server=127.0.0.1;port=3306;uid=root;pwd=123456;database=WireCloud;", "provider": "MySql.Data.MySqlClient" } }
添加UserService相关类:
namespace PetaPocoEfCoreMvc.Service { using PetaPocoEfCoreMvc.Models; public interface IUserService { IEnumerable<User> GetAll(); } } namespace PetaPocoEfCoreMvc.Service { using PetaPoco; using PetaPocoEfCoreMvc.Models; public class UserService:IUserService { private readonly IDatabase _database; //构造函数注入 public UserService(IDatabase database) { _database = database; } public IEnumerable<User> GetAll() { return _database.Fetch<User>(); } } }