I am following this tutorial Youtube DI for dependency injection. This clear thing out for me however it does not show how to implement on a Web API using n-tier architecture. I also included followed this tutorial: C-Sharp AutoFac Web API Tutorial.
This is what my code look like:
using Autofac;
using System.Linq;
using System.Reflection;
using System.Web.Http;
namespace WebAPI.App_Start
{
public class AutofacWebapiConfig
{
public static IContainer Container;
public static void Initialize(HttpConfiguration config)
{
Initialize(config, RegisterServices(new ContainerBuilder()));
}
public static void Initialize(HttpConfiguration config, IContainer container)
{
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
private static IContainer RegisterServices(ContainerBuilder builder)
{
//Register your Web API controllers.
//builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(Assembly.Load(nameof(Coordination)))
.Where(t => t.Namespace.Contains("Services"))
.As(t => t.GetInterfaces().FirstOrDefault(i => i.Name == "I" + t.Name));
//Set the dependency resolver to be Autofac.
Container = builder.Build();
return Container;
}
}
}
The issues I have here is that AutofacWebApiDependencyResolver is missing.
And this is where I place my code to call the AutofacWebapiConfig class
namespace CB.WebAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//Dependency Injection
//Configure AutoFac
AutofacWebapiConfig.Initialize(GlobalConfiguration.Configuration);
// Web API routes
...
}
}
}
This is a brand new web api core with 3 class library doing a n-tier architecture. Any help would be appreciated. Is it at the right location to call it, do I need to create a third class.
I also added a classed Bootstrapper in my app_start folder, and I modified Global.asax to add a line Bootstrapper.Run();
In the comments you have said that the namespace AutofacWebApiDependencyResolver belongs to (Autofac.Integration.WebApi) doesn't exist when you try and add a using directive for it.
It would appear that your project doesn't have the Autofac.Webapi2 NuGet package installed.
To install it using Visual Studio:
Alternatively, in Visual Studio 2019 you install it with this simple procedure:
AutofacWebApiDependencyResolver