tech2avinash
tech2avinash

Reputation: 73

How create a instance of class with dependent in constructor from startup.cs(ASP.NET Core)

I'm trying to create email client in my asp.net core web application.I have created a class with some DB service as dependent and I have a method inside this class which will connect to the mail box and starts listening to it on a separate thread.But I'm unable to create an instance of the class from the startup.cs file because I unable pass IDBxxxxService to the constructor.

  var serviceProvider = Services.BuildServiceProvider();
        serviceProvider.CreateInstance<MailEvents>().MailSubscribe(new IMAPConnection
        {
            Host = "imap.gmail.com",
            EnableOAuth = false,
            Port = 993,
            EnableSSL = true,
            UserName = "xxxxxxxxxxx",
            Password = "9xxxxxxxxxxxxxx",
        });

and here is extension method i have written to create the instance using reflection.

public static TResult CreateInstance<TResult>(this IServiceProvider provider) where TResult: class
    {
        ConstructorInfo constructor = typeof(TResult).GetConstructors()[0];

        if (constructor != null)
        {
            object[] args = constructor
                .GetParameters()
                .Select(o => o.ParameterType)
                .Select(o => provider.GetService(o))
                .ToArray();

            return Activator.CreateInstance(typeof(TResult), args) as TResult;
        }

        return null;
    }

Upvotes: 2

Views: 3379

Answers (1)

Nkosi
Nkosi

Reputation: 247008

Let's assume your class looks something like

public class MailEvents {
    public MailEvents(IDbxxxService db) {
        //...
    }
}

Register all the other dependencies with the service collection in the composition root.

Services.AddSingleton<IDbxxxService, DbxxxService>(); //Choose appropriate lifetime
Services.AddSingleton<MailEvents>();

That way when asking for your service the service provider will have all it needs to hydrate the object graph.

var serviceProvider = Services.BuildServiceProvider();
serviceProvider.GetService<MailEvents>().MailSubscribe(new IMAPConnection
{
    Host = "imap.gmail.com",
    EnableOAuth = false,
    Port = 993,
    EnableSSL = true,
    UserName = "xxxxxxxxxxx",
    Password = "9xxxxxxxxxxxxxx",
});

You can also use one of the overloaded methods as well

//if you need to manually create dependency you have that option as well
//in case you needed to add other customizations.
Services.AddSingleton<IDbxxxService>(provider => new  DbxxxService()); //Choose appropriate lifetime

Upvotes: 3

Related Questions