vendredi 24 janvier 2020

How to improve factory approach to be able to register dependencies in a right way

I need a code refactoring advice. I have a class which contains several dependencies. I will just provide a constructor, but this should be enough. The class implements this interface:

public interface ITopicPublisher<T> {} 

and the class itself:

public class TopicPublisher<T> : ITopicPublisher<T>
{
    public TopicPublisher(IEventGridClient eventGridClient, string topicEndpoint) { ... }
}

Now, the instance of this class is injected to the Controllers like this:

public class SomeController : Controller
{
     public SomeController(ITopicPublisher<MyEntity> publisher) { ... }
}

in order to create EventGridClient, I need to construct it like this (where key is a simple string):

new EventGridClient(new TopicCredentials(key))

Now, the topicEndpoint and key are taken from Environment.GetEnvironmentVariable(...). It all now is problematic when registering dependencies in ASP.NET (2.2) Startup.cs.

builder.Services
    .AddScoped(x => new TopicPublisher<MyEntity>(new EventGridClient(
        new TopicCredentials(Environment.GetEnvironmentVariable("KEY"))),
        Environment.GetEnvironmentVariable("ENDPOINT")))

I didn't like it, so I created a factory, like this:

public class EnvironmentVariableTopicPublisherFactory
{
    public static ITopicPublisher<T> Create<T>(string topicUrlEnvironmentVariable, string keyEnvironmentVariable) where T : class =>
        new TopicPublisher<T>(new EventGridClient(new TopicCredentials(Environment.GetEnvironmentVariable(keyEnvironmentVariable))), 
            Environment.GetEnvironmentVariable(topicUrlEnvironmentVariable));
}

and now the registration process seem to be a little more simple:

builder.Services
    .AddScoped(x => EnvironmentVariableTopicPublisherFactory.Create<MyEntity>("ENDPOINT", "KEY"))

I have some concerns however, that I could do it better. Could you give me some hint, how this approach can be made more clean, if this is possible?

Aucun commentaire:

Enregistrer un commentaire