How to Register MediatR in .NET 6 Web API where MediatR UsecCses are in separate project - .net-6.0

I am working on C# Web API 6.0 project with MediatR. Since I am following clean architecture, I have separate project for Web API and Application. I have useCases in Application project with Queries, Commands and handler.
I have register MediatR to WebApplicationBuilder with reference of class 'ApplicationAssembly'. The 'ApplicationAssembly' class is inside Application project.
API Service Contrainer
public static class ServicesConfigurator
{
public static void Configure(WebApplicationBuilder builder)
{
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAutoMapper(typeof(ApplicationAssembly));
builder.Services.AddMediatR(typeof(ApplicationAssembly).GetTypeInfo().Assembly);
}
The above code don't work the way I register MediatR
Exception thrown: 'System.AggregateException' in Microsoft.Extensions.DependencyInjection.dll
if I changed to
builder.Services.AddMediatR(typeof(Program));
then I get following error
One or more errors occurred. (Error constructing handler for request of type MediatR.IRequestHandler`2[SalaryTracker.Application.UseCases.User.Queries.GetUser, SalaryTracker.Application.WrapperDTOs.UserWrapperDataView]. Register your handlers with the container. See the samples in GitHub for examples.)

Related

How to stop generating dynamic web api?

I have downloaded template and creating sample task application.
From below reference I found Web API auto generated from my task service class.
Dynamic web api generation
So how can I stop this behaviour or make changes in this behavior.
You can easily disable an application service to expose its methods as Web API actions.
Just use [RemoteService(false)] attribute on application service class or application service interface.
[RemoteService(IsEnabled = false)]
public class UserAppService : ApplicationService, IUserAppService
{
}
for mass operation, use #aaron's method.
Comment out the lines mentioned on that page.
ASP.NET MVC 5
// Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder
// .ForAll<IApplicationService>(typeof(AbpProjectNameApplicationModule).Assembly, "app")
// .Build();
https://github.com/aspnetboilerplate/module-zero-template/blob/c0d7f0433d573a8207b27f817e1d188c215f1e50/src/AbpCompanyName.AbpProjectName.WebApi/Api/AbpProjectNameWebApiModule.cs#L17-L19
ASP.NET Core
// Configuration.Modules.AbpAspNetCore()
// .CreateControllersForAppServices(
// typeof(AbpProjectNameApplicationModule).GetAssembly()
// );
https://github.com/aspnetboilerplate/module-zero-core-template/blob/bb9d5aab6e5047d6d22d49831b473c0b3329b499/aspnet-core/src/AbpCompanyName.AbpProjectName.Web.Core/AbpProjectNameWebCoreModule.cs#L44-L47

Asp.Net Core Project Combine Web and Windows Service

Is it possible to have a service API that can handle API request / responses, but also have an internal service running on a timer. e.g Every 2 hours check database Logs and delete info logs, something like that?
Asp.Net Core is like any other .NET Core application, it has a Main function where you can start all non-blocking operations you want.
In Program.cs:
public static void Main(string[] args)
{
//Here you can start your timer (maybe using a dedicated class)
//Just avoid blocking code...
//Starting Asp.Net Core web host.
BuildWebHost(args).Run();
}
If you find more confortable, you can do the same inside Configure/ConfigureServices methods in your Startup.cs file, hopefully creating a specific service for your purpose.

Http.EnumRouteContraint must implement System.Web.Routing.IRouteConstraint

I'm using AttributeRouting in my Web API project. I've installed the AttributeRouting for Web API. I want to define an Enum route constraint so I setup my AttributeRoutingHttpConfig config as follows:
using System.Reflection;
using System.Web.Http;
using AttributeRouting.Web.Http.Constraints;
using AttributeRouting.Web.Http.WebHost;
using MyProject.Data.Models;
[assembly: WebActivator.PreApplicationStartMethod(typeof(PhantasyTour.AttributeRoutingHttpConfig), "Start")]
namespace MyProject
{
public static class AttributeRoutingHttpConfig
{
public static void RegisterRoutes(HttpRouteCollection routes)
{
routes.MapHttpAttributeRoutes(
config =>
{
config.AddRoutesFromAssembly(Assembly.GetExecutingAssembly());
config.InlineRouteConstraints.Add("ListType", typeof(EnumRouteConstraint<ListType>));
});
}
public static void Start()
{
RegisterRoutes(GlobalConfiguration.Configuration.Routes);
}
}
}
When I fire up my application I immediately receive the following error:
The constraint "AttributeRouting.Web.Http.Constraints.EnumRouteConstraint`1[[MyProject.Data.Models.ListType, MyProject.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]" must implement System.Web.Routing.IRouteConstraint
I've looked at the source code for the AttributeRouting.Web.Http.Constraints.EnumRouteConstraint and confirmed that it implements IHttpRouteConstraint which presumably is the WebAPI equivalent of IRouteConstraint in the MVC namespace.
Does anyone know what I'm doing wrong and how I can get this working?
UPDATE:
I attempted to create a completely blank Web Application and add only WebAPI and AttributeRouting for WebAPI references. Despite having absolutely no references to MVC assemblies, I still receive the same error message. I did discover however that there is another EnumRouteConstraint found in the AttributeRouting.Web.Constraints namespace which works perfectly. It doesn't appear to be MVC specific since it is located in the Core AttributeRouting assembly. I would love to know why there are two different EnumRouteConstraint classes when only one of them works. But that is a question for another time.
It is interesting that the exception you get refers to the MVC interface from the namespace System.Web.Routing.
I would take it as a clue and look at all the references in your project, any place in the config where MVC Routes and Http Routes could have been mixed up.
If possible and if you have any at all, try removing all references to MVC (or System.Web.Routing for a start), and MVC flavour of attribute routing (if it's a separate dll).

Web API Self hosting from a test assembly

I'm currently evaluating WebAPI and NancyFx for a new project about to start. I've managed to get Nancy to self host from a test assembly (by itself it uses asp.net hosting).
Is there any way to do the same with Web API? I would like to keep the web api project hosted on IIS, but i would like to spin it up from my test assembly, so i can run tests against it.
I have found some blogposts on how to use Autofac to scan controllers from another assembly (seems a little backwards only to get hosting from another assembly to work, but if it can be done, i guess that would be an option), but i would like to keep using Structuremap ioc for this project.
Managed to get it working with help from Mark Jones link. This is what i ended up with in my test assembly.
private static HttpSelfHostServer _server;
[BeforeTestRun]
public static void Setup()
{
var config = new HttpSelfHostConfiguration(Settings.TestUri);
WebApiConfig.Register(config); //map routes
IocConfig.Bootstrap(config); //configure dependency injection
_server = new HttpSelfHostServer(config);
_server.OpenAsync().Wait();
}
[AfterTestRun]
public static void TearDown()
{
_server.CloseAsync().Wait();
}

How to enable Dependency Injection for ServiceRoute in MVC3 and WCF Web API

I am creating a MVC3 website that will expose a REST API using WCF Web API.
To register routes to the REST API I add code to the Global.asax similar to the code below.
routes.MapServiceRoute<RelationsService>("relations");
This works well enough but i need to use a DI approach to inject the dependencies that the Service depends on.
As you can see in the code above the MVC framework is creating the instance of the RelationsService but this should be done by the DI container.
Does anyone know how to configure MVC3 so that my own DI container is used for creating the instances of the Services?
You have to extend your current service registration call with an IHttpHostConfigurationBuilder that has been created with an IResourceFactory.
var configurationBuilder = HttpHostConfiguration.Create()
.SetResourceFactory(new ResourceFactory());
routes.MapServiceRoute<RelationsService>("relations", configurationBuilder);
Then if you for instance use StructureMap as preferred IoC/DI tool you can just ask for the service in the GetInstance method.
public class ResourceFactory : IResourceFactory
{
public object GetInstance(Type serviceType, InstanceContext instanceContext, HttpRequestMessage request)
{
return ObjectFactory.GetInstance(serviceType);
}
}

Resources