MEF plugin Lucky airship Platform rental development-powerful DI in Dotnetcore

Source: Internet
Author: User
Tags dotnet

Background narrative
In the previous few lucky airship platform rental (www.1159880099.com) QQ1159880099 MEF Plug-in development series blogs, I experimented with MEF's simple experiments in DotNet framework and DotNet Core two frameworks, due to do The Tnet framework is long-standing, so there are many excellent MEF frameworks derived from this framework. But for DotNet Core, the situation is different, because it itself has built-in and support for DI, so I tried to use its new dependency injection (DI) to do some experiments.

Hands-On Labs
To allow the program to support DI, you need to install the package for your project:

Install-package Microsoft.extensions.dependencyinjection-version 2.1.1
Then we can use the powerful DI.

In DotNet Core, the registration of all services is uniformly put together, and this is received by servicecollection; second, when the service is registered, the service needs to be initialized, and the resulting result is returned as a service provider with the corresponding type serviceprovider; Finally, if you get a registered service, you can get it through Serviceprovider.getservice ().

Below, I'll take a look at the powerful DI in DotNet Core from the following 4 different aspects.

Inject and set the service life cycle
The registration service needs to relate to the life cycle of the service, so iservicecollection has 3 different extension methods:

AddTransient: Each access to the service is newly created;
Addscoped: The services obtained within a certain range are the same;
Addsingleton: Each access to the service is the same, singleton mode of service;
The sample code looks like this:

public interface Ibasesender
{
void Send (String message);

}

Public interface Itransientsender:ibasesender {}
public class Transientsender:itransientsender
{
public void Send (String message) = Console.WriteLine ($ "{GetHashCode ()} {message}");
}

Public interface Iscopedsender:ibasesender {}
public class Scopedsender:iscopedsender
{
public void Send (String message) = Console.WriteLine ($ "{GetHashCode ()} {message}");
}

Public interface Isingletonsender:ibasesender {}
public class Singletonsender:isingletonsender
{
public void Send (String message) = Console.WriteLine ($ "{GetHashCode ()} {message}");
}

Class program
{
private static readonly object locker = new Object ();
static void Main (string[] args)
{
var serviceprovider = new Servicecollection ()
. Addtransient<itransientsender, transientsender> ()
. Addscoped<iscopedsender,scopedsender> ()
. Addsingleton<isingletonsender, singletonsender> ()
. Buildserviceprovider ();

    using (var scope = serviceProvider.CreateScope())    {        for (int i = 0; i < 2; i++)        {            serviceProvider.GetService<ITransientSender>().Send("ITransientSender");            scope.ServiceProvider.GetService<IScopedSender>().Send("IScopedSender");            serviceProvider.GetService<ISingletonSender>().Send("ISingletonSender");        }    }    Console.WriteLine("***********************************");    using (var scope = serviceProvider.CreateScope())    {        for (int i = 0; i < 2; i++)        {            serviceProvider.GetService<ITransientSender>().Send("ITransientSender");            scope.ServiceProvider.GetService<IScopedSender>().Send("IScopedSender");            serviceProvider.GetService<ISingletonSender>().Send("ISingletonSender");        }    }    Console.ReadKey();}

}
The program output looks like this:

Through what we can learn,

In the same or different scopes, services registered through AddTransient are newly created each time;
Within the same scope, services registered through addscoped each time the same; in different request scopes, services registered through addscoped are newly created each time;
Services registered through Addsingleton are the same throughout the entire program life cycle;
It is important to note that all EF-related services in ASP. NET Core should be injected in a addscoped<tinterface,t> manner. In addition, if you want to inject generics, you can inject it with the TypeOf method.

Constructor injection
Parameter injection

public interface Ibasesender
{
void Send ();
}

public class Emialsender:ibasesender
{
Private readonly string _msg;
Public Emialsender (string msg) = _msg = msg;

public void Send() => Console.WriteLine($"{_msg}");

}

Class Program
{
static void Main (string[] args)
{
var serviceprovider = new Servicecollection ()
. Addsingleton<ibasesender, emialsender> (factory = {return new Emialsender ("Hello World");})
. Buildserviceprovider ();

    serviceProvider.GetService<IBaseSender>().Send();    Console.ReadKey();}

}
Service Injection

public interface Ibasesender
{
void Send ();
}

public class Emialsender:ibasesender
{
Private ReadOnly IWorker _worker;
Public Emialsender (IWorker worker) = _worker = worker;

public void Send() =>_worker.Run("Hello World");

}

public interface IWorker
{
void Run (String message);
}

public class Worker:iworker
{
public void Run (String message)
{
Console.WriteLine (message);
}
}

Class Program
{
private static readonly Object locker = new Object ();
static void Main (string[] args)
{
var serviceprovider = new Servicecollection ()
. Addsingleton<ibasesender, Emialsender> ()
. Addsingleton<iworker, Worker> ()
. Buildserviceprovider ();

    serviceProvider.GetService<IBaseSender>().Send();    Console.ReadKey();}

}
Developed under the traditional DotNet framework, injection is supported for parameters, services, and attributes, but only the first two injections are currently supported under the DotNet Core platform.

Add log records
The Logger functionality has been integrated in DotNet Core and can be eaten with the appropriate package installed.

Microsoft.Extensions.Logging
Microsoft.Extensions.Logging.Console
Microsoft.Extensions.Logging.Debug
The sample program looks like this:

public interface Ibasesender
{
void Send ();
}

public class Emialsender:ibasesender
{
Private ReadOnly IWorker _worker;
Private ReadOnly ilogger<emialsender> _logger;

public EmialSender(IWorker worker, ILogger<EmialSender> logger){    _worker = worker;    _logger = logger;}public void Send(){    _worker.Run("Hello World");    _logger.LogInformation(MethodBase.GetCurrentMethod().Name);}

}

public interface IWorker
{
void Run (String message);
}

public class Worker:iworker
{
public void Run (String message)
{
Console.WriteLine (message);
}
}

Class Program
{
private static readonly Object locker = new Object ();
static void Main (string[] args)
{
var serviceprovider = new Servicecollection ()
. Addsingleton<ibasesender, Emialsender> ()
. Addsingleton<iworker, Worker> ()
. Addsingleton (New Loggerfactory (). Addconsole (). Adddebug ())
. Addlogging ()
. Buildserviceprovider ();

    serviceProvider.GetService<IBaseSender>().Send();    Console.ReadKey();}

}
Summarize
Some of the little experiments that were done were interesting and experienced a powerful DI feature in DotNet Core. There are many improvements compared to the traditional DotNet Framework, which is a new technology that deserves every DotNet programmer to try.

MEF plugin Lucky airship Platform rental development-powerful DI in Dotnetcore

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.