Tags down


How to initialize a scoped injected class in ASP.NET Core involving asynchronous calls

By : Tayum
Date : September 17 2020, 01:00 AM
it helps some times In this case you will need to forgo the property and have an asynchronous method.
This would also mean having an asynchronous lazy initialization for the User using
code :
/// <summary>
/// Provides support for asynchronous lazy initialization.
/// </summary>
/// <typeparam name="T"></typeparam>
public class LazyAsync<T> : Lazy<Task<T>> {
    /// <summary>
    ///  Initializes a new instance of the LazyAsync`1 class. When lazy initialization
    ///  occurs, the specified initialization function is used.
    /// </summary>
    /// <param name="valueFactory">The delegate that is invoked to produce the lazily initialized Task when it is needed.</param>
    public LazyAsync(Func<Task<T>> valueFactory) :
        base(() => Task.Run(valueFactory)) { }
public sealed class AspNetUserContext : IUserContext {
    private readonly UserManager<User> userManager;
    private readonly IHttpContextAccessor accessor;
    private readonly LazyAsync<User> currentUser;

    public AspNetUserContext(IHttpContextAccessor accessor, UserManager<User> userManager) {
        this.accessor = accessor;

        if (userManager == null)
            throw new ArgumentNullException(nameof(userManager));

        this.userManager = userManager;

        currentUser = new LazyAsync<User>(() => this.userManager.FindByIdAsync(Id.ToString()));

    public string Name => accessor.HttpContext.User?.Identity?.Name;
    public int Id => accessor.CurrentUserId();

    public Task<User> GetCurrentUser() {
        return currentUser.Value;
User user = await context.GetCurrentUser();
public Task<User> CurrentUser => currentUser.Value;
User user = await context.CurrentUser;

Share : facebook icon twitter icon

What is the best practice in EF Core for using parallel async calls with an Injected DbContext?

By : Silence
Date : March 29 2020, 07:55 AM
wish help you to fix your issue It came to the point where really the only way to answer the debate was to do a performance/load test to get comparable, empirical, statistical evidence so I could settle this once and for all.
Here is what I tested:

How to Throttle all outgoing asynchronous calls to HttpClient across multiple threads in .net Core API project

By : Fazel Akbari
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Conceptual questions SemaphoreSlim is thread-safe so there are no thread-safety or locking concerns about using it as a parallelism throttle across multiple threads. HttpMessageHandlers are indeed an outbound middleware mechanism to intercept calls placed through HttpClient. So they are an ideal way to apply parallelism-throttling to Http calls using SemaphoreSlim. Simple implementation
So a ThrottlingDelegatingHandler might look like this:
code :
public class ThrottlingDelegatingHandler : DelegatingHandler
    private SemaphoreSlim _throttler;

    public ThrottlingDelegatingHandler(SemaphoreSlim throttler)
        _throttler = throttler ?? throw new ArgumentNullException(nameof(throttler));

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        if (request == null) throw new ArgumentNullException(nameof(request));

        await _throttler.WaitAsync(cancellationToken);
            return await base.SendAsync(request, cancellationToken);
int maxParallelism = 10;
var throttle = new ThrottlingDelegatingHandler(new SemaphoreSlim(maxParallelism)); 
HttpClient throttledClient = new HttpClient(throttle);
int maxParallelism = 10;
services.AddSingleton<ThrottlingDelegatingHandler>(new ThrottlingDelegatingHandler(new SemaphoreSlim(maxParallelism)));

var client = _clientFactory.CreateClient("MyThrottledClient");
int maxParallelism = 10;
var throttler = Policy.BulkheadAsync<HttpResponseMessage>(maxParallelism, Int32.MaxValue);

var throttler = Policy.BulkheadAsync<HttpResponseMessage>(10, 100);

How to integrate Quartz.Net jobs that require "scoped" services injected in them (ASP.NET Core 2.0)?

By : 谢正才
Date : March 29 2020, 07:55 AM
I wish this helpful for you I am trying to create some Quartz.Net jobs following my own answer from this question. However, if the job is fairly complex and required "scoped" (services.AddScoped<.., ...>) services, the example does not work because jobs are created as singletons. , For resoving scoped service from IServiceProvider, try
code :
    using (var scope = _serviceProvider.CreateScope())
        var job = (IJob)scope.ServiceProvider.GetService(jobDetail.JobType);            

Changing whether a service is injected as scoped or transient via the .Net Core DI container at runtime?

By : WoodleySaint
Date : March 29 2020, 07:55 AM
this will help I think the core of your issue lies in the following observation:

.NET Core EF, when to avoid asynchronous database calls

By : reza
Date : March 29 2020, 07:55 AM
To fix the issue you can do Async in MVC is about freeing up the request handling threads so that they can respond to additional requests. It doesn't make code faster, it actually makes it slightly slower. When it comes to threads, it's fairly easy to see what it is doing in that it hands off to a worker thread. What happens after that async method completes depends on the synchronization context. In most cases it will resume on the worker thread.
So using [thread#] prefixes:
code :
[1] using(var context = new AppContext())
[1]     var orders = await context.Orders
            .Where(x => x.CustomerId == customerId)
            .OrderBy(x => x.OrderDate)
[2]     foreach(var order in orders)
Related Posts Related Posts :
  • SQL Command Parameter cannot covert string to int
  • Azure Notification Hub example to register a device and receive a notification
  • Disabed element shown as enabled in Selenium C#
  • Html.listboxfor() how to capture event on change/add item - Jquery MVC (C#)
  • c# Accessing my array inside a class constructor
  • How to first 'Split a string to an Array' then 'Add something to that Array'? || C# Console App
  • IEnumerable of Tuple of string of string
  • Why don't I get a warning about possible dereference of a null in C# 8 with a class member of a struct?
  • Visual Studio 2019: how to disable specific CodeAnalysis messages in .editorconfig?
  • Pass ID to controller on prev or next
  • What are the difference using app.run and app.useendpoints in asp.net-core?
  • Why string Method(Object object) may not match Func<Object, string> delegate type?
  • Check inside loop if *txt file has been created
  • C# retry logic While loop
  • Convert object {object[]} to string[]
  • Difference between initialize a string to "" or to "".ToString() - Which one should I use?
  • How to make the console wait but then continue without pressing a Key?
  • extract text in rich text format from range
  • how to handle 1000 concurrent user requests per second in asp.net web api
  • In C# How to get Windows Credentials from credential manager
  • Override default value of null conditional operator
  • How to fix override ToString method
  • System.IO.FileNotFoundException when creating EF migrations on .net core
  • Login limit attempts in C#
  • Loop into ListView elements
  • Changing Blazor folder gives me "Cannot find the fallback endpoint"
  • creating class from JSON with different types of a node
  • How to define models for Database tables in C# without using Linq To DB?
  • Understanding Identityserver4 with Identity (cookies/tokens, server architecture)
  • How to Deserialize a JSON into a list using SIMPLE JSON?
  • another option instead using AsEnumerable() in linq EF, when using custom method in linq
  • Parameterized query that returns TEXT column(s) always returns zero for INT columns
  • Why format is not working while appending zeros?
  • SqlConnection string
  • Entity Framework Core Update Database - Code First Approach Without Migration
  • Unity Update Method
  • Custom Middleware is causing Blazor Server-side page to stop working
  • Declaring hex number: The name 'B9780' does not exist in the current context
  • Invalid cast from 'System.Int32' to Enum using reflections
  • Why does my webrequest line need updating? (error (426) Upgrade Required )
  • How to generate Key and Key IV aes in C#
  • How can I display view inside content control in wpf
  • How can I wait for form2 to finish?
  • Is Application.DoEvents() a form of Multitasking?
  • In C#, how can I see if the first character in an account is a specific value?
  • C# Determine if a char at index is between two characters in a string
  • C# - Winform Timer - Disposing and emptying the timer
  • if else condition in Regex c# and return constant value
  • Ternary operator for 3 conditions
  • Fineuploader with Azure, Empty image problem
  • How do I unit test the event raised by class under test?
  • How to set up .net core service that uses a generic repository
  • ASP.NET Core 3.0 Endpoint Routing doesn't work for default route
  • use gmail API token on localhost and hosting at the same time
  • Try-catch FormatException
  • why do sql procedure retuns 0 rows when called from applciation?
  • .Net core 3: The namespace internal does not exist in Microsoft.Extensions.Logging.Internal
  • how to interpolate a variable into string method
  • I want to instantiate an object at the location of another object which is destroyed
  • How to display full path of ALL currently running process in C#?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk