Unity - 解析从 T 继承的泛型实现
本文关键字:继承 泛型 实现 Unity | 更新日期: 2023-09-27 18:35:21
我正在使用 Unity,并希望解析所有具有可从特定类型分配的泛型类型的实现。
我目前像这样进行注册:
container.RegisterType<IQueryGenerator<IPerson>, PersonQueryGenerator>("1");
container.RegisterType<IQueryGenerator<ICustomer>, CustomerQueryGenerator>("2");
container.RegisterType<IQueryGenerator<IEmployee>, EmployeeQueryGenerator>("3");
container.RegisterType<IQueryGenerator<IManager>, ManagerQueryGenerator>("4");
然后层次结构是这样的:
public interface IPerson
{
}
public interface ICustomer : IPerson
{
}
public interface IEmployee : IPerson
{
}
public interface IManager : IEmployee
{
}
以及我试图解决的实现接口:
public interface IQueryGenerator<T>
{
IEnumerable<Expression<Func<T, bool>>> GenerateQueries();
}
现在,我希望能够解析所有 IQueryGenerators,其中泛型类型可分配给我拥有的类型。所以我有一个工厂应该包装它:
public class QueryFactory
{
private readonly IUnityContainer _container;
public QueryFactory(IUnityContainer container)
{
_container = container;
}
public IEnumerable<Expression<Func<TModel, bool>>> GenerateQueries<TModel>()
{
// Get all querygenerators which can handle TModel.
IQueryGenerator<TModel>[] queryGenerators = _container.ResolveAll<IQueryGenerator<TModel>>();
foreach (var queryGenerator in queryGenerators)
{
// Do something with queryGenerator.
var result = queryGenerator.GenerateQueries();
}
}
}
我想要的是_container.ResolveAll<IQueryGenerator<IEmployee>>()
返回PersonQueryGenerator
、EmployeeQueryGenerator
和ManagerQueryGenerator
,因为IManager
是IEmployee
,而IEmployee
是IPerson
。
_container.ResolveAll<IQueryGenerator<ICustomer>>()
返回PersonQueryGenerator
,并CustomerQueryGenerator
。
IEmployee
可以铸造成IPerson
,可以由PersonQueryGenerator
处理。
如何注册 IQueryGenerators,以及如何根据TModel
解析它们?或者是否有任何其他方法可以根据TModel
实现的接口检索查询生成器?
编辑:
我添加了我想做什么的概念证明。它运行良好,但编码非常困难。
class Program
{
static void Main(string[] args)
{
IEnumerable<IManager> managers = new List<IManager>
{
new Manager()
{
Birthday = DateTime.Now.AddDays(1),
Name = "Executive Manager",
EmployeeNumber = 9,
IsExecutive = true,
Salary = 1000
},
new Manager()
{
Birthday = DateTime.Now.AddDays(-1),
Name = "Ordinary Manager",
EmployeeNumber = 8,
IsExecutive = false,
Salary = 900
},
};
var queries = GenerateQueries();
managers = queries.Aggregate(managers, (current, expression) => current.Where(expression));
foreach (var manager in managers)
{
Console.WriteLine("Manager: {0}", manager.Name);
}
Console.ReadKey();
}
// Change this to a generic method.
static IEnumerable<Func<IManager, bool>> GenerateQueries()
{
// Change this to a more generic management
IList<IQueryGenerator<IManager>> queryGenerators = new List<IQueryGenerator<IManager>>();
if (typeof(IPerson).IsAssignableFrom(typeof(IManager)))
{
queryGenerators.Add(new PersonQueryGenerator());
}
if (typeof(IEmployee).IsAssignableFrom(typeof(IManager)))
{
queryGenerators.Add(new EmployeeGenerator());
}
if (typeof(IManager).IsAssignableFrom(typeof(IManager)))
{
queryGenerators.Add(new ManagerQueryGenerator());
}
// Fetch queries and return them.
var queries = new List<Func<IManager, bool>>();
foreach (var queryGenerator in queryGenerators)
{
// Do something with queryGenerator.
queries.AddRange(queryGenerator.GenerateQueries());
}
return queries;
}
// I want to use this method instead.
static IEnumerable<Func<TModel, bool>> GenerateQueries<TModel>()
{
// Do the same thing as the method above
//TODO: Resolve all IQueryGenerators that can handle TModel.
return null;
}
}
public interface IQueryGenerator<in T>
{
IEnumerable<Func<T, bool>> GenerateQueries();
}
public class ManagerQueryGenerator : IQueryGenerator<IManager>
{
public IEnumerable<Func<IManager, bool>> GenerateQueries()
{
Console.WriteLine("ManagerQueryGenerator called");
yield return x => x.IsExecutive;
}
}
public class PersonQueryGenerator : IQueryGenerator<IPerson>
{
public IEnumerable<Func<IPerson, bool>> GenerateQueries()
{
Console.WriteLine("PersonQueryGenerator called");
yield return x => x.Birthday > DateTime.Now;
}
}
public class EmployeeGenerator : IQueryGenerator<IEmployee>
{
public IEnumerable<Func<IEmployee, bool>> GenerateQueries()
{
Console.WriteLine("EmployeeGenerator called");
yield return x => x.Salary > 900;
}
}
public interface IHaveName
{
string Name { get; set; }
}
public interface IPerson : IHaveName
{
DateTime Birthday { get; set; }
}
public interface ICustomer : IPerson
{
int MoneyToSpend { get; set; }
}
public interface IEmployee : IPerson
{
int EmployeeNumber { get; set; }
int Salary { get; set; }
}
public interface IManager : IEmployee
{
bool IsExecutive { get; set; }
}
public class Manager : IManager
{
public string Name { get; set; }
public DateTime Birthday { get; set; }
public int EmployeeNumber { get; set; }
public int Salary { get; set; }
public bool IsExecutive { get; set; }
}
输出为:
PersonQueryGenerator called
EmployeeGenerator called
ManagerQueryGenerator called
Manager: Executive Manager
这就是我想要的,但使用更通用的类型管理,我真的很想使用 Expression<Func<T,bool>>
,因为它将与 EF 一起使用。
public interface IQueryGenerator<T>
{
IEnumerable<Expression<Func<T, bool>>> GenerateQueries();
}
而不是:
public interface IQueryGenerator<in T>
{
IEnumerable<Func<T, bool>> GenerateQueries();
}
当您填充 Unity 容器时,可以通过一点点反射来实现。
private static UnityContainer container = new UnityContainer();
static void RegisterGenerator<T, TG>() where TG : IQueryGenerator<T>
{
var assembly = typeof(T).Assembly;
// walk trough all interfaces in assembly, if the interface inherits from
// typeof(T), add that particular IQueryGenerator<> to container as well
foreach (var type in assembly.GetTypes())
{
if (typeof(T).IsAssignableFrom(type) && type.IsInterface)
{
var generatorType = typeof(IQueryGenerator<>).MakeGenericType(type);
container.RegisterType(generatorType, typeof(TG), type.Name);
}
}
}
static IEnumerable<Func<T, bool>> GenerateQueries<T>() where T : IPerson
{
var queryGenerators = container.ResolveAll<IQueryGenerator<T>>().ToList();
// Fetch queries and return them.
var queries = new List<Func<T, bool>>();
foreach (var queryGenerator in queryGenerators)
{
// Do something with queryGenerator.
queries.AddRange(queryGenerator.GenerateQueries());
}
return queries;
}
例:
static void Main(string[] args)
{
RegisterGenerator<IPerson, PersonQueryGenerator>();
RegisterGenerator<IManager, ManagerQueryGenerator>();
var managers = new List<IPerson>
{
new Manager
{
Birthday = DateTime.Now.AddDays(1),
Name = "Executive Manager",
EmployeeNumber = 9,
IsExecutive = true,
Salary = 1000
},
new Manager
{
Birthday = DateTime.Now.AddDays(-1),
Name = "Ordinary Manager",
EmployeeNumber = 8,
IsExecutive = false,
Salary = 900
}
}.AsEnumerable();
var queries = GenerateQueries<IPerson>();
managers = queries.Aggregate(managers, (current, expression) => current.Where(expression));
foreach (var manager in managers)
{
Console.WriteLine("Manager: {0}", manager.Name);
}
Console.ReadKey();
}
using System;
using System.Collections.Generic;
using System.Linq;
using Unity;
namespace ConsoleApplication1
{
internal class Program
{
private static UnityContainer container = new UnityContainer();
private static void Main(string[] args)
{
container.RegisterType<Manager>(new ContainerControlledLifetimeManager());
container.RegisterType<IPerson, Manager>();
container.RegisterType<IEmployee, Manager>();
container.RegisterType<IManager, Manager>();
container.RegisterType<IQueryGenerator<IPerson>, PersonQueryGenerator>();
container.RegisterType<IQueryGenerator<IEmployee>, EmployeeGenerator>();
container.RegisterType<IQueryGenerator<IManager>, ManagerQueryGenerator>();
IEnumerable<IManager> managers = new List<IManager>
{
new Manager()
{
Birthday = DateTime.Now.AddDays(1),
Name = "Executive Manager",
EmployeeNumber = 9,
IsExecutive = true,
Salary = 1000
},
new Manager()
{
Birthday = DateTime.Now.AddDays(-1),
Name = "Ordinary Manager",
EmployeeNumber = 8,
IsExecutive = false,
Salary = 900
},
};
// Fetch queries and return them.
var queries = new List<Func<IManager, bool>>();
queries.AddRange(GenerateQueries<IPerson>());
queries.AddRange(GenerateQueries<IEmployee>());
queries.AddRange(GenerateQueries<IManager>());
managers = queries.Aggregate(managers, (current, expression) => current.Where(expression));
foreach (var manager in managers)
{
Console.WriteLine("Manager: {0}", manager.Name);
}
Console.ReadKey();
}
// I want to use this method instead.
private static IEnumerable<Func<TModel, bool>> GenerateQueries<TModel>()
{
var queryGenerator = container.Resolve<IQueryGenerator<TModel>>();
return queryGenerator.GenerateQueries();
}
}
public interface IQueryGenerator<in T>
{
IEnumerable<Func<T, bool>> GenerateQueries();
}
public class ManagerQueryGenerator : IQueryGenerator<IManager>
{
public IEnumerable<Func<IManager, bool>> GenerateQueries()
{
Console.WriteLine("ManagerQueryGenerator called");
yield return x => x.IsExecutive;
}
}
public class PersonQueryGenerator : IQueryGenerator<IPerson>
{
public IEnumerable<Func<IPerson, bool>> GenerateQueries()
{
Console.WriteLine("PersonQueryGenerator called");
yield return x => x.Birthday > DateTime.Now;
}
}
public class EmployeeGenerator : IQueryGenerator<IEmployee>
{
public IEnumerable<Func<IEmployee, bool>> GenerateQueries()
{
Console.WriteLine("EmployeeGenerator called");
yield return x => x.Salary > 900;
}
}
public interface IHaveName
{
string Name { get; set; }
}
public interface IPerson : IHaveName
{
DateTime Birthday { get; set; }
}
public interface ICustomer : IPerson
{
int MoneyToSpend { get; set; }
}
public interface IEmployee : IPerson
{
int EmployeeNumber { get; set; }
int Salary { get; set; }
}
public interface IManager : IEmployee
{
bool IsExecutive { get; set; }
}
public class Manager : IManager
{
public string Name { get; set; }
public DateTime Birthday { get; set; }
public int EmployeeNumber { get; set; }
public int Salary { get; set; }
public bool IsExecutive { get; set; }
}
}