0

I have a code snippet that creates an instance based on the configuration specified in the JSON file (I am thinking about LoginLogic)

public ILoginModule GetLoginModule()
{
    if (loginModule == null)
    {
        loginModule = new LoginModule.LoginModule(_configuration);

        Type loginLogicType = CreateTypeFromConfiguration("LoginModule", "LoginLogic", "MyProject.Modules.LoginModule.Logic.LoginLogic");
        loginModule.SetLoginLogic((ILoginLogic)Activator.CreateInstance(loginLogicType));
    }
    return loginModule;
}

Here's what the LoginLogic class looks like

public class LoginLogic : ILoginLogic
{
    private IConfiguration _configuration;
    protected ILoginRepository loginRepository;

    public LoginLogic()
    {
    }

    public LoginLogic(IConfiguration configuration)
    {
        _configuration = configuration;
        loginRepository = new LoginRepository(_configuration);
    }
}

Activator uses an empty constructor to create an object

I need to have the data that I call in the next constructor

loginRepository I can move because it does not change anything

What to do with configuration? It is injected automatically by Net. Core

1
  • We obviously can't see a lot of your custom code here, but it looks like you're just reinventing the wheel of Configure<TOptions>. Why not use what's already built in? Commented Jul 19, 2019 at 18:25

1 Answer 1

5

There is a little known static class in NetCore which allows you to the CreateInstance but with injection..

From the top of my head, I think its in the Microsoft.Extensions.DependencyInjection.Abstractions namespace and its called ActivatorUtilities.

You call it like so:

var instance = ActivatorUtilities.CreateInstance(ServiceProvider, typeof(typeToInstantiate));

It requires a IServiceProvider instance which contains all the objects it can inject for.

Is that what you're looking for?

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.