[英]Process list of object by type
I have a requirement to create a Sync method. 我需要创建一个Sync方法。 1) On input it takes SyncRequest object.
1)输入时,将使用SyncRequest对象。
class SyncRequest{
public List<SyncObj> Objects{get;set;}
}
class SyncObj{
public Type Type{get;set;}
public object Object{get;set;}
}
2) Based on type of each object i need to use different service to proceed and the different repository to persist the data. 2)根据每个对象的类型,我需要使用不同的服务来进行操作,并需要使用不同的存储库来持久化数据。
Ie if i got the 3 objects with types User, User, Task. 即,如果我得到3个对象,类型分别为User,User,Task。 I will group them by type, and then Proceed with UserService and TaskService.
我将按类型对它们进行分组,然后继续执行UserService和TaskService。
I'm trying to architect my web.api with Onion Architecture. 我正在尝试使用Onion Architecture构建我的web.api。 Where DataAccess, Core, Services are separated of each other.
DataAccess,Core,Service彼此分开的地方。 And i want avoid swich or if's, in my code.
我想在我的代码中避免使用swich或if。
All ideas i came up was ugly. 我提出的所有想法都很丑陋。 For example
Dicitionary<Type, Service>
, and manual casting. 例如
Dicitionary<Type, Service>
和手动转换。
I feel that Ninject might have really beatifull answer on my problem, with some factory functionality, but i can't come up with it. 我觉得Ninject可能具有某些工厂功能,对我的问题确实很满意,但是我无法提出。
Can anyone describe how this pattern should work. 谁能描述这种模式应该如何工作。 Or how this pattern calls, where to read.
或该模式如何调用,在何处读取。
Since all you've got is a Type
one way or another you're going to have to use Reflection. 由于您所拥有的只是一种或另一种
Type
您将不得不使用Reflection。 The other question is how you're accessing the DI container (ninject kernel). 另一个问题是您如何访问DI容器(ninject内核)。
You can do something like this: 您可以执行以下操作:
public interface IHandler<T>
{
void Handle(T obj);
}
public void UserService : IHandler<User> {...}
Bind<IHandler<User>>().To<UserService>();
which you would then use like this: 然后您将使用以下代码:
foreach(var syncObj in syncRequest.Objects)
{
Type handlerType = typeof(IHandler<>).MakeGeneric(syncObj.Type);
MethodInfo handleMethod = handlerType.GetMethod("Handle");
object handler = kernel.Get(handlerType);
handleMethod.Invoke(handler, new object[] { syncObj.Object });
}
As you see you'll need access to the container somehow to create the specific type. 如您所见,您将需要以某种方式访问容器以创建特定类型。 You can have it injected as
IResolutionRoot
. 您可以将其作为
IResolutionRoot
注入。 To adhere to the Onion Layering you'll have to move the code that uses the kernel to the composition root and give it an interface... Since you seem to know about onion layering i won't go into more detail :) 要坚持洋葱分层,您必须将使用内核的代码移至组合根并为其提供一个接口...因为您似乎对洋葱分层有所了解,所以我不再赘述:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.