lundi 29 juin 2020

Reuse various entities in different services

In my WPF application, I have a situation where I dont't know what pattern/technique shall be used in order to reuse/share various entities in different services of views.

I'll try to describe this with some C# pseudo-code:

public class ViewModelA : ViewModelBase
{
    private IParserService parserService;
    
    ViewModelA(IParserService parserService)
    {
        // Injected via DI
        this.parserService = parserService; 
    }
    
    private void ParseDataFromFile(string fileName)
    {
        string extension = Path.GetExtension(fileName);

        // Only xml and json are relevant, so no need for the strategy design pattern
        switch(extension)
        {
            case ".xml":
            var entityA = parserService.ParseXml();
                break;
            case ".json":
            var entityB = parserService.ParseJson();
                break;
        }

    }
}

public class EntityA
{
    public int IntA { get; set; }
    public string StringA { get; set; }
}

public class EntityB
{
    public string StringB1 { get; set; }
    public string StringB2 { get; set; }
}

public class ServiceB
{
    // ServiceB will use the EntityA and EntityB
    // EntityA and EntityB shall be available at the application restart
}

public class ServiceC
{
    // ServiceB will use only the EntityB
    // EntityB shall be available at the application restart
}

Now, based on the code snippet above, I try to reuse entities EntityA & EntityB in different services that are invoked from different viewmodels. Since the parsing procedures of both, the ParseXml() and ParseJson() might take quite a long processing time and in addition they shall be available after the application restart, I don't know how to reuse/share this entities between different services (or viewmodels).

My first thought was to simply serialize the parsed entities and deserialze them afterwards in each service class that requires it, like so:

public class ServiceB
{
    ServiceB()
    {
        var entityA = Deserialize(string filePathToEntityA);
        var entityB = Deserialize(string filePathToEntityB);
    }
}

public class ServiceC
{
    ServiceC()
    {
        var entityB = Deserialize(string filePathToEntityB);
    }
}

But this, imo, creates some kind of weird and unusable structure...

So, what I'm looking for, is a practical approach in C# on how to solve this kind of problem.

Aucun commentaire:

Enregistrer un commentaire