Suffixes of Some Class Names in C# and Their Meanings

2020年3月14日 62点热度 0人点赞 0条评论
内容目录

C# has common types with the following suffixes, and the author has summarized their general uses.

  • Extensions
  • Helper or Helpers
  • Scheme
  • Builder
  • Context
  • Factory
  • Provider
  • Options
  • Defaults

Extensions

This type is used to implement extension methods, with the class name suffixed by Extensions.

For example, the implementation of an extension method is represented by what we commonly use: app.UseAuthentication();.

    public static class AuthAppBuilderExtensions
    {
        public static IApplicationBuilder UseAuthentication(this IApplicationBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }           
            return app.UseMiddleware<AuthenticationMiddleware>();
        }
    }

Helper or Helpers

This refers to utility classes that generally hold no special significance, used to indicate that this type is for completing certain auxiliary operations, such as some conversions or serialization. In most cases, these are set as static classes.

For example, a utility class that handles Uri in Microsoft.AspNetCore.Cors.Infrastructure.

    internal static class UriHelpers
    {
        public static bool IsSubdomainOf(Uri subdomain, Uri domain)
        {
            return subdomain.IsAbsoluteUri 
                && domain.IsAbsoluteUri
                && subdomain.Scheme == domain.Scheme
                && subdomain.Port == domain.Port
                && subdomain.Host.EndsWith($".{domain.Host}", StringComparison.Ordinal);
        }
    }

Scheme

Represents a scheme, category, or handling method, generally used in enumerations or to specify the usage of a certain type, mostly constants.

For example, in ASP.NET Core, the original configuration code for Jwt authentication is as follows:

            services.AddAuthentication(options=>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
           // Cookie     CookieAuthenticationDefaults.AuthenticationScheme

Builder

This type follows the builder pattern, typically used for functional programming to chain method calls to create a certain type.

Its purpose is to abstract the process of constructing a complex object, using different processes to build different parts of the object.

For example, StringBuilder is used for building strings. Additionally, in ASP.NET Core, the construction process of IHost is as follows:

        public static void Main(string[] args)
        {
            ConsoleToke();
            var host = CreateHostBuilder(args).Build();
            host.Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

Context

Context refers to various contexts such as the HTTP request context, access context, thread context, etc.

For example, DbContext in EFCore, HttpContext in HTTP requests, and CurrentContext in multithreading.

Factory

The factory pattern serves to provide an interface for creating a set of related or dependent objects without specifying their concrete classes.

For example, in the service injection process of ASP.NET Core:

        private static ServiceProvider serviceProvider;
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            // ...
            // ...  
            serviceProvider = services.BuildServiceProvider();
        }

        // Retrieve any instance that implements the TInterface interface
        public TInterface GetAnyInterface<TInterface>()
        {
            return serviceProvider.GetService<TInterface>();
        }

In the following code, a type can be dynamically instantiated and returned as needed.

            public static Func<T> CreateFactory<T>(Type implementation)
            {
                return ((IActivator<T>)Activator.CreateInstance(typeof(AlgorithmActivatorCore<>).MakeGenericType(implementation))).Creator;
            }

Provider

The provider pattern was invented by Microsoft.

I searched for this for a long time and found information on Wikipedia https://en.wikipedia.org/wiki/Provider_model.

The design and specifications of the provider pattern can be referenced in Microsoft documentation https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/ms972319(v=msdn.10)?redirectedfrom=MSDN.

Here is an exercise tutorial https://www.c-sharpcorner.com/uploadfile/webmaster3/provider-design-patterns-in-Asp-Net-2-0/.

https://www.codemag.com/Article/0711081/The-Provider-Model.

Options

Originally a model type for some configurations.

For example, in ASP.NET Core, the type that records Jwt authentication configurations.

 public class JwtBearerOptions : AuthenticationSchemeOptions
    {
        public bool RequireHttpsMetadata { get; set; } = true;
        public string MetadataAddress { get; set; }
        public string Authority { get; set; }
        public string Audience { get; set; }
		... ...
    }

Defaults

Defines constants and default values.

    public static class JwtBearerDefaults
    {
        public const string AuthenticationScheme = "Bearer";
    }

痴者工良

高级程序员劝退师

文章评论