Unity not registering - model-view-controller

I'm using unity in my MVC app
I have the following RegisterTypes method within my Bootstapper.cs file:
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<AccountController>(new InjectionConstructor());
container.RegisterType<IModelContext, ModelContext>();
container.RegisterType<IModelRepository, ModelRepository>();
}
I have the following controller:
public class APIScoresController : ApiController
{
private IModelRepository _repo;
public APIScoresController(IModelRepository repo)
{
_repo = repo;
}
public IEnumerable<Result> Get()
{
return _repo.GetResults();
}
}
I have the following Model Repo:
public class ModelRepository : IModelRepository
{
ModelContext _ctx;
public ModelRepository(ModelContext ctx)
{
_ctx = ctx;
}
public IQueryable<DomainClasses.Result> GetResults()
{
return _ctx.Results;
}
}
When I try to execute the GET on the APIScoresController I get the following exception:
An error occurred when trying to create a controller of type 'APIScoresController'. Make sure that the controller has a parameterless public constructor
I would have expected unity to create the required ModelContext and ModelRepository objects. Any ideas why it's not doing this?

Problem caused by web api registration needing a different version of system.web.http. I was trying to add web api to an existing mvc5 app - bad idea! I entered a form of dll hell that I hadn't experienced since days of VB6 COM. In the end my solution was to create a new solution with a web api project then retro fit the mvc project.

Related

How to access Identity UserManager in Web API Controller to Send an Email

I am using Identity v2 and need to send an Email from Web Api Controller using the UserManager.SendAsync method which is OWIN Middleware component. But I don't know how do I access the UserManager itself in Web Api Controller Method. I am trying a similar approach like a Regular MVC controller but usermanager always null. Any suggestion please?
public class MyApiController: ApiController
{
public MyApiController()
{
}
public MyApiController(ApplicationUserManager userManager)
{
UserManager = userManager;
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public void SendEmail()
{
_userManager.SendAsync(...);
}
}
The constuctor that takes a ApplicationUserManager will never be called with your current solution. Change your empty constructor to call your other constructor.
public class MyApiController: ApiController
{
public MyApiController()
: this(new ApplicationUserManager())
{
}
THE REST OF YOUR IMPLEMENTATION GOES HERE
}
Check whether you have correctly configured UserManager from Startup class
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
using Owin;
namespace Identity_PasswordPolicy
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
///...
// Configure the UserManager
app.UseUserManagerFactory(new IdentityFactoryOptions<ApplicationUserManager>()
{
DataProtectionProvider = app.GetDataProtectionProvider(),
Provider = new IdentityFactoryProvider<ApplicationUserManager>()
{
OnCreate = ApplicationUserManager.Create
}
});
/// ...
}
}
}
Like here in Startup.Auth class from asp.net identity samples
https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/Identity-PasswordPolicy/Identity-PasswordPolicy/App_Start/Startup.Auth.cs
Startup is partial class and method ConfigureAuth by link is called from https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/Identity-PasswordPolicy/Identity-PasswordPolicy/Startup.cs
In sample it is called from owin startup method, but depending from hosing it could be called from global.asax.cs

load repository with constructor parameters in Web API (1)

I'm trying to get the following scenario using autofac but I'm not sure how my code will be built to get this up & running.
I have a repository class, this repository class needs to get a project key (string) on initialization (constructor). I want to instantiate this repository in initialization of my "Initialize" method provided to my by Web Api, because the project key will be available in my route.
so instead of calling "new ProductRepository(projectKey)", I want to use Autofac. Can someone point me in the right direction? I didn't find any way to send in specific data to the container in web api, since the container/builder is only available in the appStart.
Should I make the container available as a singleton so that I can approach it, or is this bad practice?
in your initialization code:
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
config.DependencyResolver = resolver;
in your controller:
public class MyController : ApiController
{
public MyController(IComponentContext container)
{
var key = new NamedParameter("projectKey", "keyFromRoute");
var repository = container.Resolve<ProductRepository>(key);
}
}
That should do it.
There is a nuget package that provides a DependencyResolver for WebApi that integrates with AutoFac. Create the DependencyResolver, assign it to the config, register your controllers in the autofac container.
I'm making some assumptions because you didn't provide your code, but I think you have something like this:
public class ProductRepository
{
public ProductRepository(DbContext dbContext, int projectKey)
{
}
}
public class SomeController : Controller
{
private readonly Func<int, ProductRepository> _repoFactory;
public SomeController(Func<int, ProductRepository> repoFactory)
{
_repoFactory = repoFactory;
}
public void DoStuff(int projectKey)
{
var repo = _repoFactory(projectKey);
repo.DoStuff();
}
}
public class RepositoryModule : Module
{
public override Load(ContainerBuilder builder)
{
builder.RegisterType<ProductRepository>();
}
}

ASP.Net MVC 3 - unitOfWork.Commit() not saving anything

I created a web application using ASP.Net MVC 3 and EF 4.1, and I am using the UnitOfWork pattern, but nothing is getting committed to the database. All this is quite new to me, and I don't know where to start to resolve this issue.
I based myself on this post to create my web application:
http://weblogs.asp.net/shijuvarghese/archive/2011/01/06/developing-web-apps-using-asp-net-mvc-3-razor-and-ef-code-first-part-1.aspx
The final code, which can be obtained here also has a service layer and the UnitOfWOrk is being injected into the services.
Instead of using the custom injector based on Unity 2 as they are in that project, I am using Unity.Mvc3.
Here is my IUnitOfWork class:
public interface IUnitOfWork
{
void Commit();
}
And here is my UnitOfWork class:
public class UnitOfWork : IUnitOfWork
{
private readonly IDatabaseFactory databaseFactory;
private MyProjectContext dataContext;
public UnitOfWork(IDatabaseFactory databaseFactory)
{
this.databaseFactory = databaseFactory;
}
protected MyProjectContext DataContext
{
get { return dataContext ?? (dataContext = databaseFactory.Get()); }
}
public void Commit()
{
DataContext.Commit();
}
}
And here is how one of my service class look like:
public class RegionService : IRegionService
{
private readonly IRegionRepository regionRepository;
private readonly IUnitOfWork unitOfWork;
public RegionService(IRegionRepository regionRepository, IUnitOfWork unitOfWork)
{
this.regionRepository = regionRepository;
this.unitOfWork = unitOfWork;
}
...
}
At start-up, my UnitOfWork component is being registered like this:
container.RegisterType<IUnitOfWork, UnitOfWork>();
Now, no matter whether I try to insert, update or delete, no request is being sent to the database. What am my missing here?
UPDATE:
Here is the content of DataContext.Commit():
public class MyProjectContext : DbContext
{
public DbSet<Region> Regions { get; set; }
public virtual void Commit()
{
base.SaveChanges();
}
}
And here is databaseFactory.Get():
public interface IDatabaseFactory : IDisposable
{
MyProjectContext Get();
}
UPDATE #2:
Using the debugger, I am noticing that my Region service and controller constructors are getting called once when performing only a select, but they are called twice when performing an update. Is this normal?
Ok, I found the culprit. It has to do with how I was registering my database factory.
Instead of
container.RegisterType<IDatabaseFactory, DatabaseFactory>();
I needed
container.RegisterType<IDatabaseFactory, DatabaseFactory>(new HierarchicalLifetimeManager());
I found the information on this web site:
http://www.devtrends.co.uk/blog/introducing-the-unity.mvc3-nuget-package-to-reconcile-mvc3-unity-and-idisposable
That's an awfully complex implementation of Unit of Work. I actually prefer this one:
http://azurecoding.net/blogs/brownie/archive/2010/09/22/irepository-lt-t-gt-and-iunitofwork.aspx
Much simpler, and much more flexible. Although you do have to work out a few things for yourself.
May just be a typo but in UnitOfWork your private MyProjectContext is called dataContext (lowercase d)
But in your commit method your calling DataContext.Commit. Any chance that's actually calling a static method that you didn't intend to call? More likely a typo but thought I'd point it out.
+1 for an overly complex implementation of UnitOfWork.

How do I inject service dependencies into MVC sitemap DynamicNodeProviderBase using StructureMap

Consider the following code:
public class InboxMenuItemDynamicProvider : DynamicNodeProviderBase
{
private IMyService _myService { get; set; }
public InboxMenuItemDynamicProvider(IActionService actionService)
{
_myService = myService;
}
public override IEnumerable<DynamicNode> GetDynamicNodeCollection()
{
// use _myService here....e.g. db access
}
}
}
How do I go about injecting a service dependency into a Mvc Sitemap DynamicNodeProvider using StructureMap and MVC3? I'm using the MVC3 dependency resolver.
However, on running the app, I get a 'no default constructor' error. I need to somehow inject service dependencies into the provider, but I'm at a total loss as to where/how I can inject them. I don't even know if its possible as Mvc Site Map might be outside of the depency resolver.
See this link:
http://mvcsitemap.codeplex.com/discussions/263971
I think you could just use:
private IMyService _myService
{
get
{
return DependencyResolver.Current.GetService<IMyService>();
}
}
and do nothing specific in your constructor

Unity dependency injection in custom membership provider

I have ASP.NET MVC3 project where I want to use custom membership provider. Also I want to use Unity for resolving my dependency injection.
this is code from Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var container = new UnityContainer();
container.RegisterType<IAuthentification, Authentification>();
container.RegisterType<IRepository, Repository>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
this is code from my membership provider:
public class CustomMembershipProvider : MembershipProvider
{
[Dependency]
private IProveaRepository Repository { get; set; }
public override bool ValidateUser(string username, string password)
{
.....
}
Problem is when I put breakpoint to ValidateUser method I see that Repository property not initialized. But this construction:
[Dependency]
private IProveaRepository Repository { get; set; }
for example, works fine in controllers.
Does anybody know why it is so and what to do?
I had the same problem over the last couple of days. I ended up with the following solution (type and field names changed to match yours).
public class CustomMembershipProvider : MembershipProvider
{
private IProveaRepository repository;
public CustomMembershipProvider()
: this (DependencyResolver.Current.GetService<IProveaRepository>())
{ }
public CustomMembershipProvider(IProveaRepository repository)
{
this.repository= repository;
}
public override bool ValidateUser(string username, string password)
{
...
}
}
So even though Unity is not in control of the building of the CustomMembershipProvider, the parameterless constructor gets Unity involed (via the MVC3 DependencyResolver) to supply the correct repository instance.
If you're unit testing the CustomMembershipProvider then you can just build an instance with Unity directly, which will use the second constructor and avoid the call to DependencyResolver.
Unity cannot inject IProveaRepository instance into you custom membership provider because :
You did not configured it to do so
CustomMembershipProvider is not resolved by unity so it has no control on injecting into it the dependencies
If you're using your membership priovider class in your code you could do the following :
Try to wrapp your customMembershipProvider in an abstraction for example IMembershipProvider that has only signature for methods that you use. The result is like that :
public class CustomMembershipProvider : MembershipProvider, IMembershipProvider
Then you could register it in unity :
container.RegisterType<IMembershipProvider, CustomMembershipProvider>(new InjectionProperty(new ResolvedParameter<IProveaRepository>()));
Then the constraint is to pass the dependency in your controller like that :
public class HomeController : Controller
{
private IMembershipProvider _membershipprovider;
public HomeController(IMembershipProvider membershipProvider)
{
_membershipProvider = membershipProvider
}
// some actions
}
But it would be event better to not user the property injection but the constructor injection like that :
public class CustomMembershipProvider : MembershipProvider
{
private IProveaRepository Repository { get; set; }
public CustomMembershipProvider(IProveaRepository proveaRepository)
{
Repository = proveaRepository
}
public override bool ValidateUser(string username, string password)
{
.....
}
It's the way I understand it and would do it. But maybe there is a better approach or I'm ignoring some of Unity API that would help to achieve it easier.
Anyway I hope it helps.
While as others said Unity cannot inject dependencies in providers because they're not known
to the container and, even if could be a registration of a provider, you haven't a "factory point" where building the provider through the container, there's a solution which doesn't violate good design principles. (This because, even if most people ignore this, using a ServiceFactory is too close to an antipattern...)
But, a good solution could be the association of using the [Dependency] attribute in conjunction with the Unity BuildUp method.
So taking your example, to get what you're trying to do, leave all the things as they are, and put in the provider constructor the BuildUp call
public class CustomMembershipProvider : MembershipProvider
{
[Dependency]
private IProveaRepository Repository { get; set; }
public CustomMembershipProvider()
{
//contextual obtained container reference
unityContainer.BuildUp(this);
.....
}
public override bool ValidateUser(string username, string password)
{
.....
}
I hope it helps.

Resources