TinkerDev
TinkerDev

Reputation: 11

Static factory method with dependency injection (.net core)

I have class structured as the following:

public interface IFooService {
  void DoStuff1();
  void DoStuff2();
}

public class FooService: IFooService {
  private string _data;

  public static FooService CreateDefault() {
    var ret = new FooService {
      _data = "Default Data"
    };

    return ret;
  }


  public static FooService CreateFromFile(string path) {
    string data = File.ReadAllText(path);

    var ret = new FooService {
      _data = data
    };

    return ret;
  }

  public static FooService CreateFromValue(string data) {
    var ret = new FooService {
      _data = data
    };

    return ret;
  }

  public void DoStuff1() {
    //
  }

  public void DoStuff2() {
    //
  }
}

Usually, I would do the following in ConfigureServices:

services.AddSingleton<IFooService, FooService>();

But in this case, how do I call a specific factory method?

It's better to create a factory class to handle the object instantiation?

It's there a better way to structure the code?

Upvotes: 1

Views: 638

Answers (1)

Neil
Neil

Reputation: 11891

You can call the factory method by using a lambda in the function:

services.AddSingleton<IFooService>(_ => factoryMethod.Create());

You can instantiate other objects, if your factory requires it (sp is the IServiceProvider):

services.AddSingleton<IFooService(sp => 
{
    var otherService = sp.GetRequiredService<IDependency>();
    return factoryMethod.Create(otherService);
});

Upvotes: 4

Related Questions