1

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?

1 Answer 1

4

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.