Using WebApi and structure map dependency injection - asp.net-mvc-4

Although there are so many question on stack overflow which tends similar to my this question but no one is resolving my problem
I was using an MVC4 internet application wherein i had few MVC controller and for dependency injection i was using Structure map. Although dependency injection works fine with MVC controller but when i added an WebApi controller in the same MVC internet application and using the same parameter in constructor of WebApi controller as what i am using in MVC controller but dependency injection is not working with WebApi controller, although if i don't use dependency injection for WebApi controller(parameterless constructor), then it works fine, but for WebApi dependency injection(parameterized constructor) it is throwing an error No parameter less constructor is found.
Conclusion depedencies are not being injected for WebApi Controller in Internet(MVC application).
Few articles suggested to use DependencyResolver.SetResolver(). i used but did not resolve the issue.

The reason why WebApi controller were not working is as following:
Since MVC Controller uses different DependenyResolver instance that is the part of System.Web.MVC .dll and within the System.Web.MVC namespace
http://msdn.microsoft.com/en-us/library/system.web.mvc.idependencyresolver(v=vs.98).aspx
Where as Api Controllers uses DependencyResolver instance that is part of System.Web.Http.
http://msdn.microsoft.com/en-us/library/system.web.http.dependencies.idependencyresolver(v=vs.108).aspx

MVC and WebAPI controllers have a different way of setting their dependency resolver. This is how I set my dependency resolver for Unity:
public void ConfigureForMvc4()
{
DependencyResolver.SetResolver(
new UnityMvc4.UnityDependencyResolver(Container));
}
public void ConfigureForWebApi()
{
GlobalConfiguration.Configuration.DependencyResolver =
new UnityWebApi.UnityDependencyResolver(Container);
}

You need to add Dependency Injection files for WebApi
Install NuGet StructureMap.WebApi2 and in the App_Start/WebApiConfig.cs file, call StructuremapWebApi.Start();
Refer: https://www.exceptionnotfound.net/setting-up-dependency-injection-in-web-api-with-structuremap/

Related

Is IHttpClientFactory registered in Asp .Net Core 3 by default?

I'm working on Asp.Net Core 3.1 project and it seems that it's possible to resolve an instance of IHttpClientFactory via DI without adding Microsoft.Extensions.Http package to my project and without registering the middleware (via AddHttpClient() method).
public ServiceClientProxy(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory; // it just works
}
In the previous versions of Asp.Net Core the additional setup was required (installing nuget, registering the middleware).
Does it mean that this service is registered in DI by default automatically under the hood in version 3.1?
Does it make sense to call AddHttpClient() explicitly in the project's middleware?
The ability to resolve IHttpClientFactory via DI without adding Microsoft.Extensions.Http package to my project can be caused by the fact that other third party services used in my project call AddHttpClient() in their code.
In case an empty Asp.Net Core 3.1 project is created, IHttpClientFactory instance cannot be resolved via DI without proper registration in Startup.cs
So it makes sense to explicitly call AddHttpClient() method in Startup.cs

Resolve a multiTenant Service outside asp.net core pipeline

Our project is using multitenancy to resolve some Service, lets say MyService based on SaasKit.
We also have a background task, which shares some of it's dependencies with the asp.net core controllers.
In the background task, any object that depends on MyService will get a null reference.
I can implement workarounds to get instances of MyService, like using service locator pattern, but this approach fails to create classes that depend on MyService without breaking DI and IOC logic.
So the question is: How can I get the same services that I can get from HttpContext with multitenancy, but get them without an HttpCoontext?

dot net core web api project templates are different

I just compared the code generated by dotnet new webapi and dotnet new angular, and checked only the web api code.
For some reason controllers derive from different classes, in project created with dotnet new webapi controller is derived from ControllerBase, while in project created with dotnet new angular controller is derived from Controller
Also the return types for actions are different, in angular template its the actual return type, while in webapi template its ActionResult
Why is that?
Which option is the "best"? And why are they different?
Before .NET Core Web API and MVC controllers were similar.
But starting with 2.0/2.1 Web API was changed.
Now you should derive class from ControllerBase instead Controller and use [ApiController] attribute.
Old style will continue to work anyway.
Angualar use Web API, I suppose, so template should be updated.
See WEb API documentation.
ControllerBase doesn't have any of the Razor/view support. ControllerBase is used for APIs.

Use DbContext in other .NET Class Library

I am using ASP.NET Core with EF Core Code First.
I am defining the dependency injection of the DbContext in service configuration of the Startup.cs of my ASP.NET Core project like described here (https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html):
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TestContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevelopmentDatabase")));
}
But I do not want to use the DbContext in a controller like described at the same site but I want to outsource it to another .NET Core Class Library project together with the Migration.
How do I accomplish this?
Implement the Repository Pattern
It's explained clearly here: Building Your First Web API with ASP.NET Core MVC
But register your repository as:
services.AddScoped<ICustomerRepository, CustomerRepository>();
instead of using .AddSingleton as the link suggests, to avoid this other problem.
I just put my xxxDbContext in a dll library project, but decided to keep migrations in the asp project:
protected override void OnConfiguring(DbContextOptionsBuilder b)
{
base.OnConfiguring(b);
b.UseSqlServer("Data Source=...", x => x.MigrationsAssembly("WebApp1"));
If you don't use MigrationsAssembly, your migrations should go to the dll I believe.
But I'm having problems using the dll in another project, I can't initiate a connection to the database

Resolving dependencies in ServiceRoute with Unity on an ASP.NET MVC project

I have a WCF service that I expose via REST using ServiceRoute in an ASP.NET MVC project:
routes.Add(new ServiceRoute("Rest", new WebServiceHostFactory(), typeof(ServeiInventaris)));
In my controllers, I use Unity to resolve dependencies. Is there a way to integrate Unity with ServiceRoute to let it resolve my dependencies (the dependencies of the REST service)?
Yes, you can. The solution is custom service host factory. Here is descibed complete solution. Neovolve blog We are using it successfully for one year.