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;
}
Aucun commentaire:
Enregistrer un commentaire