简体   繁体   中英

What is the ServiceCollectionExtensions class used for in .Net Core?

I'm coming from the full .net framework and I'm starting using .Net Core. In every project I have seen so far I always see a class named ServiceCollectionExtensions. However, when I create a new project from scratch this file is not there. So I was wondering if this class is part of the .Net Core structure or is it just a convention, and what is the use of it.

Its used to extend the ServiceCollection class so that additional "extension" methods can be written and used to simplify the Dependency Injection configuration.

Theres a far better (detailed) explanation here: https://dotnetcoretutorials.com/2017/01/24/servicecollection-extension-pattern/

It's not a standard part of ASP.NET Core, though ASP.NET Core employs many such ServiceCollection extension classes internally for various things. The name also is not magical in any way; it's just convention to name an extension class [Whatever is being extended]Extensions . In this case, ServiceCollection is being extended, so the class is typically named ServiceCollectionExtensions . You can call it FooBarBaz for all it matters, though.

As far as extending ServiceCollection , in general, goes, it's just a way to encapsulate a common set of functionality in a simple method, just like any extension of any class. For example, you might have string extension like:

public static class StringExtensions
{
    public static int ToInt32(this string s) =>
        int.TryParse(s, out var i) ?  i : 0;
}

Then, instead of having to always write this ternary, you can just do:

myStr.ToIn32();

The same goes for extensions of ServiceCollection . For example, the AddDefaultIdentity<TUser> method is actually an extension, which does the following:

services.AddAuthentication(o =>
{
    o.DefaultScheme = IdentityConstants.ApplicationScheme;
    o.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies(o => { });

services.AddIdentityCore<TUser>(o =>
{
   o.Stores.MaxLengthForKeys = 128;
   configureOptions?.Invoke(o);
})
    .AddDefaultUI()
    .AddDefaultTokenProviders();

You could do all that directly in Startup.ConfigureServices , but just calling services.AddDefaultIdentity<ApplicationUser>() is obviously much easier and succinct.

In short, if there's large blocks of related service registrations, you can create your own extension method to encapsulate all that, and then just call your extension method, making your Startup class far easier to read and understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM