JeroenZenM
JeroenZenM

Reputation: 5

How to register MediatR in WPF application

I'm experimenting with DDD in an MVVM application.

It is a basic customer system. When I add an address I want to validate it does not exist in the database.

This can be done by using a Domain Event in the Customer entitity

    public async Task<ErrorOr<Success>> AddAdress(AddAddressCommand addAddressCommand)
    {
       await DomainEvents.Raise(new AddingAddress(addAddressCommand));    

       return Result.Success;
   }

The AddAddressCommand is:

    public class AddAddressCommand
    {
        public Address Address { get; set; }
        public AddAddressCommand(Address address) 
        {
           Address = address;
        }
    }

with the following Address class:

    public record Address(AddressType AddressType,
    string StreetName, 
    string HouseNumber, 
    string HousenumberAddition, 
    string PostalCode, 
    string Residence
    ) 
    {
       public AddressType AddressType { get; set; } = AddressType;        
       public string StreetName { get; set; } = StreetName;        
       public string HouseNumber { get; set; } = HouseNumber;        
       public string HouseNumberAddition { get; set; } = HousenumberAddition;        
       public string PostalCode { get; set; } = PostalCode;        
       public string Residence { get; set; } = Residence;                
    }

I'm using MediatR to handle this kind of events using this class

    public static class DomainEvents
   {
        public static Func<IMediator> Mediator { get; set; }
        public static async Task Raise<T>(T args) where T : INotification
        {
          var mediator = Mediator.Invoke();
          await mediator.Publish<T>(args);
        }
}

When I arrive here the Mediator instance is not found!

I register the Mediator instance im my app.xaml.cs like: ServiceLocator.Default.RegisterType<IMediator, Mediator>();

ServiceLocator is part of the Catel MVVM framework.

I find numerous examples how to register MediatR, but all are Web API based.

I cannot figure out how to register MediatR properly.

The app.xaml.cs and the domainevents are in separate assemblies.

I've tried to locate the service like

    public static class DomainEvents
    {
        public static Func<IMediator> Mediator { get; set; }
        public static async Task Raise<T>(T args) where T : INotification
        {
            var mediator = ServiceLocator.Default.ResolveType<IMediator>();
            mediator = Mediator.Invoke();
            await mediator.Publish<T>(args);
         }
    }

But this still leaves with the error of IMediator not found

I supposse I need something like ServiceLocator.Default.RegisterType<IMediator>(AddMediatR(cfg => { cfg.RegisterServicesFromAssembly(typeof(Program).Assembly)))}

but I cannot get this to work.

Upvotes: 0

Views: 78

Answers (0)

Related Questions