mardi 30 mai 2017

Dynamically creating object based on type

I have the following code:

public async Task DispatchAsync(NoticeChannelType type, string message)
    {
        switch (type)
        {
            case NoticeChannelType.Email:
                {
                    var email = JsonConvert.DeserializeObject<NoticeEmail>(message);
                    await _channelResolver.ResolveAsync(email);
                }
                break;
            case NoticeChannelType.Pushover:
                {
                    var pushover = JsonConvert.DeserializeObject<NoticePushover>(message);
                    await _channelResolver.ResolveAsync(pushover);
                }
                break;
            default:
                break;
        }
    }

I would like to remove this switch somehow, create and cast the object to the concrete type.

After that the channelResolver.ResolveAsync is implemented as follows:

public async Task ResolveAsync<T>(T channel) where T : INoticeChannel
    {
        if (channel == null)
            throw new ArgumentNullException(nameof(channel),
                $"Channel: '{typeof(T).Name}' cannot be null.");

        var handler = _context.Resolve<INoticeExecutor<T>>();

        await handler.SendAsync(channel);
    }

I was trying to refactor it to something like this:

public async Task DispatchAsync(NoticeChannelType type, string message)
    {
        var channel = _context.ResolveKeyed<INoticeChannel>(type);

        Type myType = Type.GetType(channel.GetType().FullName);

        await _channelResolver.ResolveAsync((INoticeChannel)JsonConvert.DeserializeObject(message, myType));
    }

but after that in the channelResolver.ResolveAsync type T is INoticeChannel and not the concrete type so the _context.Resolve<INoticeExecutor<T>>(); can`t resolve it.

Is this possible to remove this switch and make this code more elegant and easier to maintain?





Aucun commentaire:

Enregistrer un commentaire