DbContext 'InRequestScope' doesn't work for custom membership provider - asp.net-mvc

I am implementing a custom ASP.NET membership provider that operates based on the custom repository class that in turn uses an Entity Framework DbContext as a mean of accessing a data.
Since this is an ASP.NET MVC application, IoC container (Ninject) is set to resolve instances of my DbContext InRequestScope.
My user data tables are a part of the single main DbContext.
Repository class is also bound to instantiate in InRequestScope. But the repository class is created by to satisfy the need of the custom MembershipProvider, which can't be set to instantiate InRequestScope. As a result, whenever I am trying to access Role data via repository, I get DbContext is already disposed exception.
Has anyone set up a similar configuration and if so, what was implemented differently to overcome the problem I am having. Thanks.

A workaround that has allowed me to continue with the project development was to manually create an instance of DbContext in Membership Provider constructor, in contrast to have Ninject inject it.
Maybe someone eventually will come up with a better approach to this particular problem, please post it here and I will remark it as an answer instead of this workaround.

Related

Does Microsoft DependencyInjection support non-constructor injection?

I am trying to incorporate Microsoft.Extensions.DependencyInjection into an existing ASP.NET 4.6.1 app.
I know that while .NET Core has it built-in, for 4.6.1 you need to create some initial classes as outlined in http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/. (The article seems to be out of date since the sample code does not show implementation of BeginScope() and Dispose() for IDependencyResolver. If anybody has more updated examples that would be appreciated.)
"Services" accessed by controllers where you are creating instances via constructors is fairly simple but my problem is when I need an instance of "something" that is from a property or method of an existing object.
For example, I have a inherited DbContext that needs an instance of System.Security.Principal.IIdentity that comes from the logged in user.
Another example is an instance of ApplicationUser. ApplicationUser inherits IdentityUser and the current user can be found by calling FindById() method of AppUserManager.
While AppUserManager can easily be instantiated using DI, how can I use DI the inject the output of the FindById() method? I cannot seem to find any documentation or sample code about this for Microsoft based framework. Other frameworks like Unity seem to support Property-based injection.
In essence, can DI be used with all existing classes or do you specifically need to code out the classes to support DI from the beginning? (i.e. only expect parameters to be passed in via constructors and make sure those instances themselves are created via constructors).
The very simple and short answer to your question "Does Microsoft DependencyInjection support non-constructor injection?" is, no.
Out-the-box Microsoft DI does not currently support property injection like other frameworks such as Ninject. If you need that feature, I suggest using those frameworks instead (I cant imagine MS has any plans to add property injection any time soon).
Your other option is to consider how you can refactor your code to use constructor injection instead which is the preferred method

Does breezesharp work with NHibernate metadata?

we've been using breeze for a long time and now I'm trying to access an existing webapi controller with a breezesharp client. Our controller is using NHibernate for data access.
On FetchMetadata the application throws an object reference not set exception on that line(24)
_schema = json["schema"]; in CsdlMetadataProcessor.
If I look at our metadata there is no schema node.
Am i missing something? Is there a different configuration for NHibernate?
edit: I also tried to export my metadata and import it with ImportMetadata on the metadatastore but it throws another exception when creating the clr type...
Thanks
Ok, this was a bug and will be fixed in the next version of breeze-sharp, out later this week.
Ok,
it's my fault. The bug with the NHibernate metadata has been fixed but my entities doesn't inherit from BaseEntity. We are heavily using breeze with a SPA and I was happy to reuse my existing code with a .net client but deriving my model entities from the BaseEntity class of Breeze is not an option.
Would it be possible to use reflection.emit or Castle DynamicProxy to create proxies of the model on the fly? That way the model could stay without any inheritance.
Thanks

How to use Identity membership with existing database (n-tier)

I've been reading various other questions about using asp.net-identity but I don't see anything concrete with regards to using it with an existing database when the project is developed in tiers. For argument's sake, say the following is true:
Solution
WebUI
Services
UserService
Data
MyDbContext
Core
User
How can I specify User (from the Core project) to be the IUserStore for the new identity provider? Am I missing something, or does this all assume that the website and the membership database always reside in the same project(or there are strict references to the Microsoft.AspNet.Identity.* libraries wherever the models reside)?
Setting up a DbContext at the WebUI layer just for authentication (and tie it in to the "MyDbContext" with a service) seems hacky. Am i missing something, or was the team just planning on this being only used in simple applications?
And feedback would be appreciated.
More Information
if it's worth mentioning:
This would be a completely new solution; I do not have old/existing aspnet_* or webpages_* tables to worry about. I'm trying to take various other custom solutions and tie them in to one solid solution, so I'm open to a lot of options. However, I would like to keep things broken out by layer (if at all possible).
Asp.net Identity Framework is set of components helping application to work with User Identity. Core framework blocks are in Microsoft.AspNet.Identity.Core assembly. The second Microsoft.AspNet.Identity.EntityFramework is the data persistence implementation for the Core framework.
Now for the n-tier application, you can define your AppUser model in any project/assembly. You need to inherit it from the Microsoft.AspNet.Identity.EntityFramework.IdentityUser. So based on your approach, you need to reference particular assembly.
Same is for the MyDbContext. You must inherit from the currently only available Persistence Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext<TUser>. Your MyDbContext can be in other project/assembly. You need to refer to your AppUser assembly too in this project/assembly.

Dependency Injection - Passing dependencies all the way down

I have an MVC application with a typical architecture...
ASP.NET MVC Controller -> Person Service -> Person Repository -> Entity Framework DB Context
I am using Castle Windsor and I can see the benefit of using this along with a ControllerFactory to create controller with the right dependencies. Using this approach the Controller gets a Service injected, which in turn knows how to construct the right Repository, which in turn knows the correct DbContext to use.
The windsor config is something like this...
dicontainer = new WindsorContainer();
dicontainer.Register(Component.For<IPersonService>().ImplementedBy<PersonService>());
dicontainer.Register(
Component.For<IPersonRepository>().UsingFactoryMethod(
() => new PersonRepository(new HrContext("connectionString"))));
It this the right way to do it? I don't like the UsingFactoryMethod, but can't think of another way.
Also, what if the Repository needed a dependency (say ILogger) that was not needed by the service layer? Does this mean I have to pass the ILogger into the service layer and not use it. This seems like a poor design. I'd appreciate some pointers here. I have read loads of articles, but not found a concrete example to verify whether I am doing this right. Thanks.
I try to avoid using factory methods (as you mentioned you felt this smelled funny). To avoid this, you could create a database session object that creates a new DbContext. Then your repositories just need to get an instance of IDbSession and use its dbContext property. Then, you can also easily control the scope of the IDbSession object (don't use singleton because it's not thread safe).
I wanted to make that point so that I could make this more important point... Make your constructors take in only objects that are registered in the DI container (no options or configurations in constructors). Options and configurations should be read/writen in classes whose sole purposes it is to read/write those values. If all classes follow this model, then your DI registration becomes easy and classes can just add whatever dependencies they need in their constructors.
If you are trying to use a third party library that has options in constructors, wrap that class in your own class that has an easy to consume constructor and uses a configuration class to read the values needed to pass to the third party library. This design also introduces a layer of abstraction between your code and the third party library which can then be used to more easily swap (or stub) third party libraries when necessary.

How can I use Windsor to inject a dependency into an ASP.NET MVC model?

I have a a model class that needs access to my repository class (used for DB access).
I have created an interface for my repository and have successfully configured Castle Windsor to inject my the appropriate IRepository-based class into my controllers via a custom ControllerFactory.
I'm having a little more trouble figuring out how to do the same thing with my model.
Does anyone know of a way to use Windsor to inject a dependency into an MVC model?
As an aside, the reason I need Windsor to handle this is because MVC automatically instantiates an instance of my model when data is posted to my controller, and this automatic instantiation doesn't allow for me to pass any constructor parameters.
You may want to take a look at MVC Contrib's Castle Binder.
However, personally, I think that Models should be simple POCO's, or dumb containers of data, free of any DI. In this approach, it is the Controller's responsibility to read, manipulate and persist data.

Resources