Ninject and Custom Membership provider Mvc3 [duplicate] - asp.net-mvc-3

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Inject repository to custom membership provider with Ninject
I have searched much about this topic too much the most close answer was here
MVC 3 ninject custom membership context disposed error
but I don't have any idea about the details all I have in my application is a domain contains my entities and abstraction for repositories and the implementation everything works fine when I use my Ninject binding like this
public class NinjectControllerFactory : DefaultControllerFactory{
readonly IKernel _kernel;
public NinjectControllerFactory(){
_kernel=new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType){
return controllerType == null
? null
: (IController) _kernel.Get(controllerType);
}
void AddBindings(){
_kernel.Bind<IŁSomeRepository>()
.To<EFSomeRepository>();
but I have no idea how to bind the customer membership provider I have read about this that I have to inject via a poperty but I don't know how, any ideas ?

First, you should be using Ninject.MVC3 rather than your own controller factory. Ninject.MVC3 takes care of hooking everything up, you just need to provide your mappings in App_Start\NinjectWebCommon.cs
Second, don't bother with using Ninject for Membership, unless you're using a custom membership provider. Even then, it's a lot less of a pain if you don't mix Ninject and Membership. I would suggest not bothering with it unless you really know what you're doing.
The problem is that Membership is a static class, that creates a static instance of the Membership Provider. This means it doesn't get destroyed at the end of the request. There are ways around this, but in general, it's just a lot easier to use Membership as-is than try to make it work with DI.
The question you linked to solves a specific problem, relating to injecting business logic into your custom membership provider. If you need to do this, then it might be a good choice. However, I find that most custom membership providers tend to be very simple.

Related

What is alternate for CreatePerOwinContext in .net core 2.1

I had a webapi in which I was using app.CreatePerOwinContext in startup.cs file but I want to migrate that webapi to .net core 2.1. So I have stuck at this point as I can't fine any alternate for CreatePerOwinContext.
Here is my webapi code:
public static UserManager<IdentityUser> Create(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context)
{
var manager = new UserManager<IdentityUser>(new UserStore());
return manager;
}
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<UserManager<IdentityUser>>(Create);
...
}
So how can I convert the above code in .net core 2.1?
That method was used as a service locator to load up dependencies and then access them throughout your code. Service location on its own is considered an anti-pattern, and is not recommended for use in the vast majority of real world situations.
Instead, people use IOC containers now to manage their dependency injection. In ASP.NET MVC Core, there's now a lightweight and "good enough" IOC container provided for you as part of the framework.
Microsoft provides an overview in this article, but the short version is that in your Startup.cs you register your dependency tree under ConfigureServices (usually using an extension method so Startup.cs doesn't get too large).
After you've registered your dependencies, you load them either through property injection, constructor injection, or method parameter injection. This results in cleaner code that is more maintainable than standard service location.
Edit:
If you truly insist on managing a service locator either because the technical debt is acceptable or because the business case warrants the current design, then I suggest you transition your work from OwinContext over to HttpContext.
In ASP.NET Core, you access the HttpContext by injecting the HttpContextAccessor into your class, and changing your OwinContext calls to pull from the key value store in HttpContext.
Instructions for injecting HttpContextAccessor can be found in this SO answer. Simply store KVPs using HttpContext.Current.Application["myObject"].
I don't recommend doing this, but I'm willing to share it because I understand the reality of deadlines vs the idealism of architecture.

Use Container/DependencyResolver in other dll

I'm trying to get myself familiar with MVC3 and autofac but I've encountered small problem that I'm having trouble resolving.
I am using autofac integrated with MVC3 and all works well, pages are loading correctly, dependencies are being injected and that's cool. What's bugging me is how to use autofac's Container or MVC's DependencyResover in class library project.
I'm trying to create static class that will help me handle domain events. I simply want to be able to call the method with event parameter and everything should be handeled by this class. Here is code:
public static IContainer Container { get; set; }
public static void Raise<T>(T e) where T : IDomainEvent
{
foreach (var eventHandler in DomainEventManager.Container.Resolve<IEnumerable<EventHandlers.Handles<T>>>())
{
eventHandler.Handle(e);
}
}
As you can see it's pretty straightforward and everything would work great if it wasn't MVC approach. Some of my dependencies are registeres as InstancePerHttpRequest (NHibernate' session), while other are registered as InstancePerDependency or SingleInstance. Thus when I try to use container created in my UI project, I get exception that there is no httpRequest tag available.
How can i reuse the Container created in web project to get access to all of it's features, including InstancePerHttpRequest and httpRequest tag?
Or maybe there is other solution to my problem? I was thinking about using delegate function to obtain event handlers, but I cannot (can I?) create generic delegate that I would not need to initialize with concrete type at time of assignment.
Why I want to do this using static class is basically every entity and aggregate or service needs to be able to raise domain event. Injecting EventManager into every one of these would be troublesome and static class is exactly what would resolve all my problems.
If anyone could help me get my head around it I would be grateful.
Cheers, Pako
You shouldn't be referencing your container directly from your app code. This looks like the Service Locator anti-pattern. The correct action is to pass your objects the services they need to do their jobs, usually done through constructor parameters. BUT... if you are going to insist on depending on a global static, then at least model EventManager as a singleton, such that usage would look like:
EventManager.Current.Raise<SomeEvent>(someObject);
and then you can set EventManager.Current equal to a properly constructed instance when your app is initialized.

MVC 3 And MEF and adding plug-ins to main application

I am a newbie to MEF and I am really mixed up! There are lot of useful articles out there and neat question and answers here in stackoverflow. I downloaded the example which #matthew-abbott has uploaded in his blog , but I dont know how to add new plug-ins or extension to extend the main web application, I mean like what you can see here.
Edited :
Also I use Entity Framework, Code First Approach and Unit of work for my data access layer application, what If my plug-ins needs data access and (I mean the plug-in has itself models) wants to use the DAL I created ? As you know every time the model changes, DbContext throws and error and tells re-create DB, Is there any way or other ORM which accepts extending DAL dynamically?
That particular example shows how we can integrate MEF with MVC3's new DependencyResolver which provides a service location mechanism for various extension points within the MVC architecture. There are a few other articles on my blog which detail more information about how a possible plugin architecture could work, these are available at:
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three
There are also a host of fantastic articles, my recommendations would be to also read:
ASP.NET MVC and the Managed Extensibility Framework (MEF) by Maarten Balliauw
Defining Web-scoped parts with MEF by Tim Roberts
MVC is a very flexible architecture, there are a myriad of ways it can be extended, but because of the nature of how ASP.NET applications run in IIS, you need to consider part lifetime very carefully. As an example, controllers can only be used for one request, so you could would need to ensure that your controllers have a specific CreationPolicy. Tim Robert's article on Web-scoped parts is a particularly good read.
Hope that is enough to point you in the right direction.
Edit: Because of the modular nature that MEF provides, it is important to ensure that your different layers are decoupled. You've specified that you are using Entity Framework, but the reality is, EF should likely only be used in your data layer. Typically the MVC architecture would promote view models over domain models. To that end, it is probably useful to use something similar to the repository pattern to define, e.g. here is a mock UserRepository:
[Export(typeof(IUserRepository))]
public class UserRepository : IUserRepository
{
public IEnumerable<UserViewModel> GetUsers()
{
// Get values here from EF as domain models
// And return them as view models?
}
}
Which we can export and inject into a controller:
[ExportController("User"), PartCreationPolicy(CreationPolicy.NonShared)]
public class UserController : Controller
{
private readonly IUserRepository _repo;
[ImportingConstructor]
public UserController(IUserRepository repo)
{
if (repo == null)
throw new ArgumentNullException("repo");
_repo = repo;
}
public ActionResult Index()
{
var users = _repo.GetUsers();
return View(users);
}
}
This is just a really simple example, but like many IoC containers, MEF also supports dependency injection. As long as a part provides a suitable export, it can be imported (either through property injection, or constructor injection) into another part at composition time.
My recommendation would be against exposing EF to your views, as this makes them explicitly dependent on it. By taking care to decouple and only expose the right types at the right layers, you architecture will become a lot more robust, flexible and testable, which makes maintaining it, and updating it a lot easier. As another quick example, here is how we could test our controller:
[Test]
public void UserController_CreatesViewResult_WithListOfUsers()
{
var mock = new Mock<IUserRepository>();
mock.Setup(m => m.GetUsers()).Returns(new[] { new UserViewModel { Name = "Matt" } });
var controller = new UserController(mock.Object);
var result = controller.Index();
Assert.That(result is ViewResult);
// Other assertions.
}
Because I haven't tightly coupled EF to my view, my controller is a lot more testable, I can mock a suitable repository and test where I need to.
The important thing is planning your architecture.

Strategies for Organizing Dependencies/IOC Containers in an MVC3 .Net app with Castle Windsor

So, I'm new to using Castle Windsor and I'm struggling with how ugly my Controllers are becoming. I've got IOC working in my project which seems to be at least half the problem for most people. Now I'm finding that I'm declaring a ton of dependencies in my controller constructors as below. Are there any good patterns for managing these so I'm not copying/pasting this into each new controller and/or section of the site I create?
public HomeController(ILocalizationService localizationService, // ugly
INewsService newService,
IAnswerService answerService,
ITwitterFeedService twitterService,
IFacebookService facebookService,
ISettingsService settingsService,
IExternalDataService externalDataService,
IUserService userService,
IInstantMessageService instantMessageService,
ICalendarService calendarService,
ILogger logger)
{
// do some stuff to link these up
}
Hope this makes sense. I can add more details if necessary to clarify.
It seems as though your controllers are doing too much. Try to make controllers more specialised, so with the exception of really common stuff like ILogger they don't need too many dependencies.
Review the action methods on the controllers, and see which ones seem to have similar behaviour and dependencies - they're candidates for moving to their own controller.
It seems you have a number of services that are basically doing similar things, such as facebook and twitter. Why not create an ISharingService that handles all your social networking stuff in a single interface?
Then you have an IUserService, which I take to be a repository of some type? If so, you might make better use of an Unit Of Work pattern that would condense all data repositories into one interface.

ASP.NET MVC Views Dependency Injection without DependencyResolver?

Is it possible to inject dependencies into an MVC ViewPage (must support layout pages) without using DependencyResolver?
I would rather not use DependencyResolver at all (I had major problems when injecting NH sessions into ActionFilters in the past (leaking all over the place)). However, I'm not sure if there is an alternative?
The other complexity I have is that the DependencyResolver needs to be tenant aware (each tenant has its own (StructureMap) container). I'm currently doing this by passing in a lazy instance of my tenant container resolver (seems this is necessary otherwise the resolver is cached):
public SmDependencyResolver(Func<ISiteContainerResolver> containerResolver)
{
this.containerResolver = containerResolver;
}
public object GetService(Type serviceType)
{
var container = containerResolver().Resolve();
If I end up using DependencyResolver should I ditch my StructureMap controller factory since it looks like DependencyResolver handles this too?
Thanks
Ben
Given that the DependencyResolver is used by so many aspects of the ASP.NET MVC framework for dependency injection your life will be easier if you use it - as you say it means you don't need your own versions of things like the controller factory.
That said, the framework is very flexible and it is always open for you to plug in your own version of things - I just prefer to create as little of my own code as possible on the KISS principle.

Resources