.Net Core中一個特別重要的特性就是依賴注入功能,那麼咱們在使用PetaPoco的時候是否也可使用依賴注入特性呢?數據庫
回答固然是能夠的啦。使用方法(兩種注入方式)以下json
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類:app
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中的數據庫鏈接字符串:ide
"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>(); } } }