using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; using Autofac; namespace ConsoleApp2 { class Program { static void Main(string[] args) { Console.WriteLine("如今演示切換數據庫的狀況"); //使用sql server var t1 = SwitchRespority("sql"); IPerson tt = t1.Resolve<IPerson>(); tt.Show(); var t2 = SwitchRespority("oracle"); IPerson tt1 = t2.Resolve<IPerson>(); tt1.Show(); Console.Read(); } /// <summary> /// 切換數據庫 /// </summary> private static IContainer SwitchRespority(string name) { var builder = new ContainerBuilder(); Type t = null; switch (name) { case "sql": t = typeof(ISql); break; case "oracle": t = typeof(IOracle); break; } var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes().Where(t1 => t1.GetInterfaces().Contains(t))) .Where(d => !d.IsGenericType) .ToArray(); builder.RegisterTypes(types).AsImplementedInterfaces(); return builder.Build(); } } public abstract class BaseEntiry { public abstract int Id { get; set; } } public interface ISql { } public interface IOracle { } /// <summary> /// 通用存儲接口 /// </summary> /// <typeparam name="T"></typeparam> public interface IRepository<T> where T : BaseEntiry { T GetById(int id); IEnumerable<T> List(); IEnumerable<T> List(Expression<Func<T, bool>> predicate); void Add(T entity); void Delete(T entity); void Edit(T entity); } /// <summary> /// 通用存儲庫實現 /// </summary> /// <typeparam name="T"></typeparam> public class Repository<T> : ISql, IRepository<T> where T : BaseEntiry { public void Add(T entity) { throw new NotImplementedException(); } public void Delete(T entity) { } public void Edit(T entity) { throw new NotImplementedException(); } public T GetById(int id) { throw new NotImplementedException(); } public IEnumerable<T> List() { throw new NotImplementedException(); } public IEnumerable<T> List(Expression<Func<T, bool>> predicate) { throw new NotImplementedException(); } } public class OracleRepository<T> : IOracle, IRepository<T> where T : BaseEntiry { public void Add(T entity) { throw new NotImplementedException(); } public void Delete(T entity) { } public void Edit(T entity) { throw new NotImplementedException(); } public T GetById(int id) { throw new NotImplementedException(); } public IEnumerable<T> List() { throw new NotImplementedException(); } public IEnumerable<T> List(Expression<Func<T, bool>> predicate) { throw new NotImplementedException(); } } public class Person : BaseEntiry { public override int Id { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } } public interface IPerson : IRepository<Person> { void Show(); } public class PersonRepository : Repository<Person>, IPerson { public void Show() { Console.WriteLine("sql server 123123"); } } public class OraclePersonRepository : OracleRepository<Person>, IPerson { public void Show() { Console.WriteLine("oracle 123123"); } } }