Will Autofac support IWebHostBuilder API in netcore 3+? - asp.net-core

https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html#asp-net-core-3-0-and-generic-hosting
It looks like Autofac only supports the generic hosting API, IHostBuilder. I wonder if the old asp netcore 2.x documentation is still relevant to asp netcore 3 applications.
Also, I found https://github.com/autofac/Autofac.AspNetCore has not been updated for a long time, so I guess Autofac has no intention to support IWebHostBuilder in the future...
Do we have any guideline about how to set up Autofac in AspNetCore 3.x using the IWebHostBuilder API?
I read about [this][https://stackoverflow.com/questions/59980827/service-fabric-aspnet-core-3-1-autofac-webhostbuilder] post, and it does not answer my question.

In ASP.NET Core 3.x they changed how dependency injection integrates and, no, the version 2.x documentation no longer applies - either in the Autofac case or in the ASP.NET case. ASP.NET Core intentionally shifted to the generic hosting model, where the web host is a layer on top of that.
It's not that Autofac "has no intention of supporting IWebHostBuilder", it's that that's not an option in ASP.NET Core 3. It changed at the framework level; that's not how you integrate with ASP.NET Core anymore. You don't attach the DI factory to the web host anymore, you attach it to the outer generic host.
You do register things in your Startup class just like in ASP.NET Core 2.
The docs you linked to explain all of that and show examples. You can also see in the Microsoft ASP.NET Core 2 to 3 migration docs that HostBuilder replaces WebHostBuilder; and that WebHostBuilder, while it might still exist, is being deprecated and you shouldn't use it.

You can create constructor parameters have IWebHostEnvironment on the Startup class and asp.net core will auto inject IWebHostEnvironment.
Register IWebHostBuilder as instance on the ConfigureContainer.
See the below code.
public class Startup
{
private readonly IWebHostEnvironment _environment;
// Auto injection IWebHostEnvironment
public Startup(IWebHostEnvironment environment)
{
_environment = environment;
}
public void ConfigureServices(IServiceCollection services)
{
// ...
}
// Autofac ID
public void ConfigureContainer(ContainerBuilder builder)
{
// Register your own things directly with Autofac, like:
builder.Register<SampleClass>();
// Register your IWebHostEnvironment
builder.RegisterInstance(_environment);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
}
}
public class SampleClass
{
private readonly IWebHostEnvironment _environment;
// If you register IWebHostEnvironment on the Startup, IWebHostEnvironment will auto inject.
public SampleClass(IWebHostEnvironment environment)
{
_environment = environment;
}
}
When you resolve the SampleClass, you can see the IWebHostEnvironment is auto injected to constructor.

Related

how to use ApplicationServices of IApplicationBuilder

I have asp.net core 3.1 web api app where I have registered a service as singleton,
services.AddSingleton<ISecretKeyReader, AzureKeyVaultReader>();
Now I am using BuildServiceProvider to register Logging like this
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ISecretKeyReader, AzureKeyVaultReader>();
services.AddLogging((builder) =>
{
var provider = services.BuildServiceProvider().GetRequiredService<ISecretKeyReader>();
});
}
This above code giving warning like,
Calling BuildServiceProvider from application code result in an additional copy of singleton service being created. Consider alternative such as dependency injection as parameter to configure.
Now I am seeing we have IServiceProvider option in IApplicationBuilder,
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var x = app.ApplicationServices;
}
But not sure how to use this in ConfigureServices. Any suggestion? Thanks!
I'm not sure if this will help solve your problem, but one,
What if you use Transient instead if Singleton ...
services.AddTransient<ISecretKeyReader, AzureKeyVaultReader>();
Or, two ..
Pass IApplicationBuilder as an argument to the ConfigureServices method, so you a third parameter to that method that will be resolved using dependency injection.

How to add global metadata to ASP.NET Core logging?

I'd like to add my app's build number to all logs in an ASP.NET Core 3.1 app that is using Application Insights for log storage. Is this possible without having to use BeginScope and EndScope everywhere? I assumed it would be part of the ConfigureLogging startup hook, but didn't see anything. I've done this in the past with Serilog's enrichers, but am not using that library currently.
You can achieve that with TelemetryInitializer. (https://learn.microsoft.com/en-us/azure/azure-monitor/app/api-filtering-sampling#addmodify-properties-itelemetryinitializer)
public class BuildNumberTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
(telemetry as ISupportProperties).Properties.Add("BuildNumber", "ValueForBuildNumber");
}
You need to add this initializer to the config, which is done like below if you are on Asp.Net Core applications.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ITelemetryInitializer, BuildNumberTelemetryInitializer >();
}

How to implement the IConfiguration interface in ASP.NET Core for Dapper usage?

I am familiar with using ASP.NET Core with EF Core, where you just define your DBContext in the ConfigureServices method from Startup.cs for DI, like so:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
However, I have been asked to add Dapper to this project (it will still use EF) but I can't even fetch the connection string. I found Brad Patton's answer here to be along the lines of what I had in mind, but he leaves the setup of the Configuration object up to the reader:
public void ConfigureServices(IServiceCollection services)
{
...
// Add the whole configuration object here.
services.AddSingleton<IConfiguration>(Configuration);
}
After googling around for a couple of hours, I still have no idea of how to implement the IConfiguration interface. Any help is appreciated.
With ASP.NET Core 2.x you no longer need to register the IConfiguration type yourself. Instead, the framework will already register it with the dependency injection container for you. So you can just inject IConfiguration in your services directly.
You can also take a look at the options pattern to see how to implement the configuration for your own service layer. So you could do it like this:
services.Configure<MyDatabaseOptions>(options =>
{
options.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
});
Assuming a MyDatabaseOptions type that you inject into your service using the options pattern.

How create a middleware with api endpoints in .NET Core

I have created the web application with the web api. The application contains some Controllers for example TodoController:
namespace TodoApi.Controllers
{
[Route("api/[controller]")]
public class TodoController : Controller
{
private readonly TodoContext _context;
public TodoController(TodoContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<TodoItem> GetAll()
{
return _context.TodoItems.ToList();
}
}
}
If I create the GET request - /api/todo - I get the list of Todos from database.
I have a list of controllers and api endpoints like above.
I would like distribute this api to another application ideally like middleware - my idea is register in Startup.cs like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddTodoApi();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseTodoApi();
}
This will be awesome use case for my api but I don't know how this controllers api endpoints rewrite like middleware and return same JSON data same approache like using classic Controllers.
How can I write the middleware in .NET Core for creating API endpoints?
Instead of the separate middleware, you may configure the MVC middleware to discovery controllers from another assembly:
// using System.Reflection;
public void ConfigureServices(IServiceCollection services)
{
...
services
.AddMvc()
.AddApplicationPart(typeof(TodoController).GetTypeInfo().Assembly);
Controllers are part of MVC middleware, they are not a separate part of request pipeline (but this is what middlewares are). When you register the custom middleware, it by default invokes on each request and you have HttpContext context as an input parameter to work with/edit
Request/Response data. But ASP.NET Core provides Map* extensions that are used as a convention for branching the pipeline.
Map branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.
Example:
private static void HandleMapTodo(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("/api/todo was handled");
});
}
public void Configure(IApplicationBuilder app)
{
app.Map("/api/todo", HandleMapTodo);
}
Note, that as middleware knows nothing about MVC middleware, you have only access to "raw" request and do not have features like model binding or MVC action filters.
Because it looks like the perfect microservices approach (similar than what my team is doing right now) I'd create a client assembly that can consume your API, the one that contains your TodoController, if you define a contract, and interface, for that API you can register it in your other assembly as it was a midleware and also you could mock that behaviour in your unit tests.
So, as I said, you could inject your client in ConfigureServices method, you can create:
public static IServiceCollection AddTodoRestClient(this IServiceCollection services)
{
services.AddSingleton<ITodoRestClient, TodoRestClient>();
return services;
}
Also consider that you will need to provide the enpoint so, it might looks like:
public static IServiceCollection AddConfiguredTodoClient(this IServiceCollection services, string todoEndpoint)
{
AddTodoClient(services);
ITodoRestClient todoRestClient = services.BuildServiceProvider().GetService<ITodoRestClient>();
// Imagine you have a configure method...
todoRestClient.Configure(services, todoEndpoint);
return services;
}
You can create those methods in a TodoRestClientInjector class and use them in Configure method on your startup.
I hope it helps
--- MORE DETAILS TO ANSWER COMMENTS ---
For me TodoClient is a Rest client library that implements calls to the ToDo API, (I've edited previous code to be TodoRestClient) methos like, i.e., CreateTodoItem(TodoDto todoItem) which implementation would call to the TodoController.Post([FromBody] item) or GetTodos() which wuold call TodoController.Get() and so on and so forth....
Regarding the enpoints... This approach implies to have (at least) two different applications (.NET Core apps), on the one hand the ASP NET Core app that has your TodoController and on the other hand a console application or another ASP NET Core API on which startup class you'll do the inyection adn the Rest client (the Todo Rest client) configuration ...
In a microservices approach using docker, in a dev environment, you'll use docker-compose-yml, but in a traditional approach you'll use concrete ports to define the endpoints...
So, imagine that you have in the second service a controller that need to use TodoController, to achieve so I'll use the above aproach and the "SecondController" would look like:
public class SecondController : Controller
{
private readonly SecondContext _context;
private readonly TodoRestClient _todoRestClient;
public TodoController(SecondContext context, ITodoRestClient todoRestClient)
{
_context = context;
_todoRestClient= todoRestClient;
}
// Whatever logic in this second controller... but the usage would be like:
_todoRestClient.GetTodos()
}
Just few final hints: it's key to minimize calls between services because it increases latency, and more and more if this happens on cascade. Also consider Docker usage, looks challenging but it is quite easy to start and, indeed, is thought to be used in scenarios that the one you presented and solutions like mine.
Again, I hope it helps.
Juan

ASP.NET Core: Can not resolve a service instance through CallContextServiceLocator.Locator.ServiceProvider

This is part of my ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
...
//bus
services.AddSingleton<IRouteMessages, MessageRouter>();
services.AddSingleton<IBus, DirectBus>();
////
...
}
I'm trying to resolve the instance of IRouteMessages interface in my RegisterCommandHandlersInMessageRouter class:
public class RegisterCommandHandlersInMessageRouter
{
...
public static void BootStrap()
{
var router = CallContextServiceLocator.Locator.ServiceProvider.GetService(typeof (IRouteMessages));
new RegisterCommandHandlersInMessageRouter().RegisterRoutes(router as MessageRouter);
}
...
}
router variable is always null. Yet in my controllers where IRouterMessages is resolved automatically (in constructors) everything is fine.
I'm not sure what other parts of my code could be useful. I will provide more details.
Don't EVER use CallContextServiceLocator, this completely beats the purpose of having dependency injection. And NEVER relay on it.
CallContextServiceLocator is only used in some of the internal ASP.NET Core and is never be supposed to be used by developers creating ASP.NET Core applications. That being said, it can be removed, made internal or inaccessible at any time which would break existing applications.
Additionally, the CallContextServiceLocator only had runtime services registered (DNX Services, deprecated anyways). Source: David Fowl from ASP.NET Core team.
Infact CallContextServiceLocator is being removed in RC2, see the announcement.
Removed support for CallContextServiceLocator. Use PlatformServices and CompilationServices instead.
Instead, only use the built-in dependency injection, like this:
public static class RegisterCommandHandlersInMessageRouter
{
...
// This is extension method now
public static void RegisterCommandHandlers(this IServiceProvider services)
{
var router = services.GetService(typeof (IRouteMessages));
new RegisterCommandHandlersInMessageRouter().RegisterRoutes(router as MessageRouter);
}
...
}
and call it in your Startup.cs
public void Configure(IServiceProvider services)
{
...
services.RegisterCommandHandlers();
...
}