nktdrkhv
nktdrkhv

Reputation: 1

Command pattern, EF Core, type casting and MS DI

How to put together this approches correctly?

Today I'm struggling with emplementing domain events, or something that looks like it. Let's say, I've got this (not a real code):

public abstract class ActionDataBase 
{ 
    int Id {get; set;} 
}

public interface ICommandHandler<T> where T : ActionDataBase
{ 
    public Task HandleAsync<T>(T actionData) 
}

And then it turns into

public class SayHelloToJohnActionData : ActionDataBase
{ 
    public string Name { get; set; } = "John" 
}

public class SayHelloToJohnActionHandler : ICommandHandler<SayHelloToJohnActionData>
{
    private SomeDeps _dep;

    public SayHelloToJohnActionHandler(SomeDeps dep) => _dep = dep;

    public Task HandleAsync(SayHelloToJohnActionData data)
    { 
        Console.WriteLine($"Hello, {data.Name}!");
    }
}

Finally I register it as a service and then make an entity for a EF Core

public class LovelyThing
{
    public int LovelyThingId  { get; set; }
    public ICollection<ActionDataBase> GoodFriends { get; set; }
}

What's the point? I know this code smells and also lack of experience, but in my mind, I want to store all essential data for some action and I want to get dependecies for it from DI container. So the last step is

foreach(var goodFriend in GoodFriends)
    await _dispatcher.Dispatch(goodFriend);

Somewhere and then:

public ActionHandlerDispatcher : IActionHandlerDispatcher
{
    private ServiceProvider _sp;

    public ActionHandlerDispatcher(ServiceProvider sp) => _sp = sp;

    public Task DispatchAsync<T>(T actionData)
    {
        // WELL....
    }
}

I've got an option for a WELL

var generic = typeof(ICommandHandler<>) 
var argType = actionData.GetType(); 
var constructed = generic.MakeGenericType(argType) 
var handler = (ICommandHandler<T>) _provider.GetRequiredService(constructed); // type casting error, because T is an ActionDataBase
await handler.Handler(actionData);

My question is how can I deal with it? I know that Command Pattern and Domain Events looks different, but this approach, I guess, should be usefull for me. I am about to store derived types form ActionDataBase in TPH way, and also it looks very extenable. But type casting part confuses me a lot.

Seems like IConverter's Convert.ChangeType is not my thing

Upvotes: 0

Views: 60

Answers (0)

Related Questions