Autofac trouble - asp.net-mvc

I'm new to using Autofac and Dependency injection and have been reading a lot on it. I'm getting an error message:"None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Evaluate.DivisionsController' can be invoked with the available services and parameters:
Cannot resolve parameter 'Evaluate.Services.DivisionService service' of constructor 'Void .ctor(Evaluate.Services.DivisionService)'."
I'm sure my issue is in the syntax I'm using for the configuration.
Here is my configuration in global.asax
//Autofac Configuration
var builder = new Autofac.ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
//builder.RegisterModule(new ServiceModule());
builder.RegisterModule(new EFModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
My EFModule:
builder.RegisterType(typeof(ApplicationDbContext)).As(typeof(IApplicationDbContext)).InstancePerRequest();
builder.RegisterType<UserProvider>().As<IUserProvider>().InstancePerRequest();
builder.RegisterType<DivisionService>().As<IDivisionService>().InstancePerRequest();
Controller:
private DivisionService _divisionService;
public DivisionsController(DivisionService service)
{
_divisionService = service;
}
Division Service:
public class DivisionService : BaseService<Division>, IDivisionService
{
//private IApplicationDbContext _context;
public DivisionService(IApplicationDbContext context)
:base(context)
{
}
ApplicationDBContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
{
private IUserProvider _user;
public ApplicationDbContext(IUserProvider user)
: base("DefaultConnection", throwIfV1Schema: false)
{
_user = user;
}
User Provider class:
public class UserProvider : IUserProvider
{
public string GetApplicationUserName()
{
return HttpContext.Current.User.ToString();
}
}

I have figured it out. The IDivisionService wasn't inheriting from the IBaseService

Related

Creating an OrmLite repository base class for ASP.NET

I'm trying to create a general base class that I can use in my whole project. I've written some code but still getting a NULL instance on my DbConnectionFactory.
I've create a ASP.Net web api project and added the AppHost file. I'm using Funq together with Simple Injector to Injector my custom services into the Api Controllers.
AppHost.cs
public class AppHost : AppHostBase
{
public AppHost() : base("Erp", typeof(AppHostService).Assembly)
{
}
public override void Configure(Container container)
{
// init
var simpleInjectorContainer = new SimpleInjector.Container();
var erpConnection = ConnectionStrings.ErpLocal;
var isLocal = HelperTools.IsLocalPath();
// check
if (isLocal)
{
erpConnection = ConnectionStrings.ErpOnline;
}
// mvc
ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
// register funq services
container.Register<IErpDbConnectionFactory>(c => new ErpDbConnectionFactory(erpConnectionString));
container.RegisterAutoWiredAs<CategoryService, ICategoryService>();
container.RegisterAutoWiredAs<ManufacturerService, IManufacturerService >();
container.RegisterAutoWiredAs<ProductService, IProductService>();
container.RegisterAutoWiredAs<ProductAttributeService, IProductAttributeService>();
container.RegisterAutoWiredAs<SpecificationAttributeService, ISpecificationAttributeService>();
//...
// simple injector services
SimpleInjectorInitializer.Initialize(simpleInjectorContainer, isLocal);
// register SimpleInjector IoC container, so ServiceStack can use it
container.Adapter = new SimpleInjectorIocAdapter(simpleInjectorContainer);
}
}
Base Class I'm trying to use
public abstract class ApiOrmLiteController : ApiController
{
IDbConnection _erpDb;
public virtual IErpDbConnectionFactory ErpDbConnectionFactory { get; set; }
public virtual IDbConnection ErpDb => _erpDb ?? (_erpDb = ErpDbConnectionFactory.OpenDbConnection());
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_erpDb?.Dispose();
}
}
Web Api Controller
public class ShippingController : ApiOrmLiteController
{
#region Fields
private readonly IOrderService _orderService;
private readonly IAddressService _addressService;
private readonly ICustomerService _customerService;
private readonly IPdfService _pdfService;
private readonly IMessageService _messageService;
private readonly ITranslationService _translationService;
#endregion Fields
#region Ctor
public ShippingController(IOrderService orderService, IAddressService addressService, ICustomerService customerService, IPdfService pdfService, IMessageService messageService, ITranslationService translationService)
{
_orderService = orderService;
_addressService = addressService;
_customerService = customerService;
_pdfService = pdfService;
_messageService = messageService;
_translationService = translationService;
}
#endregion Ctor
[HttpGet]
[System.Web.Http.Route("Test")]
public void Test()
{
var products = ErpDb.Select<Category>();
}
}
You may need to use constructor injection for Web API or MVC controllers, alternatively you can access dependencies in ServiceStack's IOC via HostContext.TryResolve<T>, e.g:
public virtual IDbConnection ErpDb => _erpDb ??
(_erpDb = HostContext.TryResolve<IErpDbConnectionFactory>().OpenDbConnection());

Configuring Autofac with ASP.NET MVC 5

I am trying to implement Dependency Injection with Autofac in an ASP.NET MVC5 Project. But I am getting the following error every time:
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyProjectName.DAL.Repository` ........
My Autofac configuration code in App_Start folder as follows:
public static class IocConfigurator
{
public static void ConfigureDependencyInjection()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<Repository<Student>>().As<IRepository<Student>>();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
In Global.asax file:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
// Other MVC setup
IocConfigurator.ConfigureDependencyInjection();
}
}
Here is my IRepository:
public interface IRepository<TEntity> where TEntity: class
{
IQueryable<TEntity> GelAllEntities();
TEntity GetById(object id);
void InsertEntity(TEntity entity);
void UpdateEntity(TEntity entity);
void DeleteEntity(object id);
void Save();
void Dispose();
}
Here is my Repository:
public class Repository<TEntity> : IRepository<TEntity>, IDisposable where TEntity : class
{
internal SchoolContext context;
internal DbSet<TEntity> dbSet;
public Repository(SchoolContext dbContext)
{
context = dbContext;
dbSet = context.Set<TEntity>();
}
.....................
}
Here is my Student Controller:
public class StudentController : Controller
{
private readonly IRepository<Student> _studentRepository;
public StudentController()
{
}
public StudentController(IRepository<Student> studentRepository)
{
this._studentRepository = studentRepository;
}
....................
}
What's wrong in my Autofac Configuration..Any Help Please??
To inject a dependency you need to have satisfied all of the dependencies for all of the pieces down the chain.
In your case, the Repository constructor cannot be satisfied without a SchoolContext.
So in your registration add:
builder.RegisterType<SchoolContext>().InstancePerRequest();
See http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-request

AutoFac DI in static class

We have a ASP.NET project, and we use AutoFac to DI.
We have a Service layer with all database queries and we need to make some queries in a static class.
This is how we register the dependencies in the Global.asax:
public class Dependencies
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
builder.RegisterModule(new ServiceModule());
builder.RegisterModule(new EfModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
public class ServiceModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(Assembly.Load("MyApp.Service")).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope();
}
}
public class EfModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType(typeof(myDataContext)).As(typeof(IMyContext)).InstancePerLifetimeScope();
}
}
And this is how we access in the controller:
public class SomeController : Controller
{
private readonly IService1 _service1;
private readonly IService2 _service2;
public SomeController(IService1 service1, IService2 service2)
{
_service1 = service1;
_service2 = service2;
}
public ActionResult Index()
{
var service = _service1.GetAll();
...
return View(searchModel);
}
}
Now we need to retrieve data from the database in a static class, so we have to call our service layer, but we don't know how to do it...we have seen this, but I don't know if it is correct, but it works.
public static Test ()
{
...
var service1 = DependencyResolver.Current.GetService<IService1>();
...
}
Also, how it would be in both, non-static and static classes?
Thanks in advance.
The problem is I have to call many of those classes from different places and I don't want to depend on having the service in order to call the class, I'd like the class to take care of everything.
In this case you should register your class with Autofac so that it gets its dependencies injected:
builder.RegisterType<MyClass>();
If the class is used several times during a single request it might be useful to register it using InstancePerLifetimeScope(), but that depends on your overall architecture. See this link to the Autofac documentation for more information.
Of course you have to change your class so that the methods are not static any more and add an constructor to get the dependencies:
public class MyClass
{
private readonly IService1 _service1;
public MyClass(IService1 service1)
{
_service1 = service1;
}
public void Test
{
// use the _service1 instance to do whatever you want
}
}
Now you can inject the MyClass dependency in your controller and use it without having to know anything about its internals or its dependencies:
public class SomeController : Controller
{
private readonly IService1 _service1;
private readonly IService2 _service2;
private readonly MyClass _myClass;
public SomeController(IService1 service1, IService2 service2, MyClass myClass)
{
_service1 = service1;
_service2 = service2;
_myClass = myClass;
}
public ActionResult Index()
{
var service = _service1.GetAll();
...
_myClass.Test();
return View(searchModel);
}
}

How do I inject Identity classes with Ninject?

I'm trying to use UserManager in a class, but I'm getting this error:
Error activating IUserStore{ApplicationUser}
No matching bindings are available, and the type is not self-bindable.
I'm using the default Startup.cs, which sets a single instance per request:
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
I'm able to get the ApplicationDbContext instance, which I believe is getting injected by Owin (Is that true?):
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private ApplicationDbContext context;
public GenericRepository(ApplicationDbContext context)
{
this.context = context;
}
}
But I can't do the same with UserManager (It throws the error shown before):
public class AnunciosService : IAnunciosService
{
private IGenericRepository<Anuncio> _repo;
private ApplicationUserManager _userManager;
public AnunciosService(IRepositorioGenerico<Anuncio> repo, ApplicationUserManager userManager)
{
_repo = repo;
_userManager = userManager;
}
}
The controller uses the UserManager like this:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
I'm using ninject to inject my other classes, but how do I inject the UserManager with it's dependencies and avoid using it like that in my controllers?
I injected It like this
kernel.Bind<IUserStore<ApplicationUser>>().To<UserStore<ApplicationUser>>();
kernel.Bind<UserManager<ApplicationUser>>().ToSelf();
And now It's working as it should.
OP's answer didn't work for me, as I was using a custom ApplicationUser class that has long as a key instead of string .
Hence, I created a generic static method the would get the OwinContext from the current HttpContext and return the desired concrete implementation.
private static T GetOwinInjection<T>(IContext context) where T : class
{
var contextBase = new HttpContextWrapper(HttpContext.Current);
return contextBase.GetOwinContext().Get<T>();
}
I then used GetOwinInjection method for injection like this:
kernel.Bind<ApplicationUserManager>().ToMethod(GetOwinInjection<ApplicationUserManager>);
kernel.Bind<ApplicationSignInManager>().ToMethod(GetOwinInjection<ApplicationSignInManager>);
If you are also using IAuthenticationManger, you should inject it like this:
kernel.Bind<IAuthenticationManager>().ToMethod(context =>
{
var contextBase = new HttpContextWrapper(HttpContext.Current);
return contextBase.GetOwinContext().Authentication;
});

Web API, odata v4 and Castle Windsor

I have WebApi project with ODataController and I'm trying to inject some dependency into MyController. I was following this blogpost by Mark Seemann.
Consider code below.
Problem is, that when is MyController creating, I got exception inside WindsorCompositionRoot Create method on this line,
var controller = (IHttpController)this.container.Resolve(controllerType);
An exception of type 'Castle.MicroKernel.ComponentNotFoundException'
occurred in Castle.Windsor.dll but was not handled in user code
Additional information: No component for supporting the service
System.Web.OData.MetadataController was found
Any idea how to fix this?
Thank you.
My controller:
public class MyController : ODataController
{
private readonly DataLayer _db;
public PrepravyController(DataLayer db)
{
_db = db;
}
}
CompositonRoot:
public class WindsorCompositionRoot : IHttpControllerActivator
{
private readonly IWindsorContainer container;
public WindsorCompositionRoot(IWindsorContainer container)
{
this.container = container;
}
public IHttpController Create(
HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
var controller =
(IHttpController)this.container.Resolve(controllerType);
request.RegisterForDispose(
new Release(
() => this.container.Release(controller)));
return controller;
}
private class Release : IDisposable
{
private readonly Action release;
public Release(Action release)
{
this.release = release;
}
public void Dispose()
{
this.release();
}
}
}
Global asax:
var container = new WindsorContainer();
container.Install(new RepositoriesInstaller());
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new WindsorCompositionRoot(container));
GlobalConfiguration.Configure(WebApiConfig.Register);
Make sure you're registering all your controllers with the container:
public class ControllerInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly().BasedOn<IController>().LifestylePerWebRequest())
.Register(Classes.FromThisAssembly().BasedOn<ApiController>().LifestylePerWebRequest());
}
}
Windsor uses installers to encapsulate and partition registration logic. It also includes a helper called FromAssembly, so you don't need to manually instantiate all your installers:
_container = new WindsorContainer();
_container.Install(FromAssembly.This());

Resources