logo
down
shadow

Net Core: ILogger in Startup Class: Encapsulate in Extension Method


Net Core: ILogger in Startup Class: Encapsulate in Extension Method

Content Index :

Net Core: ILogger in Startup Class: Encapsulate in Extension Method
Tag : chash , By : David B
Date : November 26 2020, 12:01 PM

this one helps. While this could not be a pure stackoverflow question, I think I can provide an opinion:
The problem with the method ConfigureServices is that you need to define all of your dependencies, for larger systems this could mean a painful long configure method, which can be really hard and boring to maintain.
public static class CommonServicesExtension
{

    public static IServiceCollection AddCommonServices(IServiceCollection services)
    {
        services.AddHttpClient();
        services.AddNodaDateTime();
        services.AddMemoryCache();
        services.AddCurrencyExchange();
        // Add and configure many things

        return services;
    }
}
CommonServicesExtension.AddCommonServices(serviceColletion);
public static IServiceCollection AddCommonServices(this IServiceCollection services)
services.AddCommonServices();
public IServiceCollection ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

    services.AddDbContext<CoreContext>(options => options.UseMySql(Configuration.GetConnectionString("Core")));
    services.AddDbContext<CoreReadOnlyContext>(options => options.UseMySql(Configuration.GetConnectionString("CORE_READONLY")));
    services.AddDbContext<StatsContext>(options =>
        options.UseMySql(Configuration.GetConnectionString("Stats")));


    services.AddScoped<ProfileTokenGenerator>();
    services.AddTransient<MailNotificationService>();
    services.AddTransient<RegisterControllerService>();

    services.AddScoped<OtherClass>();
    services.AddTransient<MoreTransient>();
    services.AddTransient<ThingsService>();

    return services;
}
public IServiceCollection ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddContexts();
    services.AddCommonServices();
    services.AddOtherServices();
    return services;
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Why ASP.NET Core DI knows how to resolve ILogger<T>, but not ILogger?


Tag : logging , By : Kilimanjaro
Date : March 29 2020, 07:55 AM
should help you out If class T contains dependency on ILogger, dependency is resolved: , Logging adds the following services to DI
services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());
services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));
public Foo(ILoggerFactory loggerFactory)
{
    _logger = loggerFactory.CreateLogger("logger name here");
}

asp.net core Trouble adding a startup extension to startup.cs


Tag : chash , By : Grace Jones
Date : March 29 2020, 07:55 AM
To fix the issue you can do You are not using the keyword this in your extension method which doesn't make it an extension method.
If you do it like this inside a static class (mandantory as well) it works just fine
    public static void EnsureMigrationsAndInitialisationRun(this IApplicationBuilder app)
    {
        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var dbContextFactory = serviceScope.ServiceProvider.GetService<IDbContextFactory>();
            var allTenantConnectionStrings = serviceScope.ServiceProvider.GetService<ISessionServices>().AllTenantConnectionStrings();

            foreach (var tenantConnectionString in allTenantConnectionStrings)
            {
                var context = dbContextFactory.CreateDbContext(tenantConnectionString);
                context.Database.Migrate();
                // Add in the initializations here.
            }
        }
    }
app.EnsureMigrationsAndInitialisationRun();

How and Who calling the ConfigureServices and Configure method of startup class in .net core


Tag : chash , By : Ohad Barzilay
Date : March 29 2020, 07:55 AM
To fix the issue you can do As everyone know that Main method of Program.cs is the entry point of application. As you can see in the .net core default code created when we create any project. , As an overly simplified explanation,
WebHost.CreateDefaultBuilder(args)

Azure function 2.x ILogger is not competible with .net core ILogger?


Tag : chash , By : Techspirit
Date : March 29 2020, 07:55 AM
this one helps. I have been trying to refer a .net core library project into my Azure function project to call one of the process defined in a .net core class library. , Update:
Have use .net core 3.0 now.
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <AzureFunctionsVersion>v2</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="librdkafka.redist" Version="1.2.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Options" Version="3.0.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.28" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>
  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <AzureFunctionsVersion>v2</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="librdkafka.redist" Version="1.2.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Options" Version="2.2.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.29" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

Accessing ILogger from non-Controller classes in Class Libary .NET Core 3


Tag : chash , By : AnToni00
Date : September 12 2020, 07:00 AM
Hope this helps Instead of instantiating a depended class inside your controller, delegate this responsibility to .NET Core inbuilt DI container - This will help you to inject the depended class directly to the required class.
Below code snippet will help you how to use DI in your existing codebase.
 public class Startup
 {
    ...
    public void ConfigureServices(IServiceCollection services)
    {      
      services.AddLogging();
      services.AddTransient<ClassX>();
      services.AddTransient<ClassY>();
      services.AddTransient<ClassZ>();
      services.AddTransient<ClassD>();
      ...
    }
}

public class ControllerB : ControllerBase
{
    private readonly ClassD classD;
    private readonly ILogger logger;

    public ControllerB(ClassD classD, ILogger<ControllerB> logger)
    {
        this.classD = classD;
        this.logger = logger;
    }
    ...
}

public class ClassD
{
   private readonly ClassZ classZ;

   public ClassD(ClassZ classZ)
   {
       this.classZ = classZ;
   }
} //Do the same thing for ClassZ and ClassY

public class ClassX
{
   private readonly ILogger logger;

   public ClassX(ILogger<ClassX> logger)
   {
       this.logger = logger;
   }
}
Related Posts Related QUESTIONS :
  • How to access .Net element on Master page from a Content page?
  • Why are unsigned int's not CLS compliant?
  • Why is Array.Length an int, and not an uint
  • How do I make event callbacks into my win forms thread safe?
  • Genealogy Tree Control
  • WCF Service - Backward compatibility issue
  • Binary patch-generation in C#
  • Tab Escape Character?
  • When do Request.Params and Request.Form differ?
  • The imported project "C:\Microsoft.CSharp.targets" was not found
  • Numeric Data Entry in WPF
  • Print a Winform/visual element
  • C# logic order and compiler behavior
  • When to use an extension method with lambda over LINQtoObjects to filter a collection?
  • How to make a button appear as if it is pressed?
  • C# and Arrow Keys
  • How do you resolve a domain name to an IP address with .NET/C#?
  • Should the folders in a solution match the namespace?
  • How can I evaluate C# code dynamically?
  • CSharpCodeProvider Compilation Performance
  • How can I create Prototype Methods (like JavaScript) in C#.Net?
  • DataTable Loop Performance Comparison
  • CSV string handling
  • What is the best way to do unit testing for ASP.NET 2.0 web pages?
  • High availability
  • What to use for Messaging with C#
  • Accessing a Dictionary.Keys Key through a numeric index
  • ConfigurationManager.AppSettings Performance Concerns
  • What Are Some Good .NET Profilers?
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com