.NET Core DI Service Collection non modifiable service for integrity - asp.net-core

I have been investing time into .NET core and the Dependency Injection model using the ServiceCollection object.
Is there any way to protect the integrity of the service implementations that have already been added to the collection?
I would like to know that the original implementation of a service I have added hasn't been modified or replaced at some point during runtime.
In the case of security, if I was an attacker who knew what I was doing and had a remote code execution vulnerability, I could replace a key service implementation and aim to hide with a form of persistence.
In the case of fool proofing, if I had a large project I would hate to have to go debugging why something went wrong to find out a developer replaces the implementation of a service that was in widespread use.
Any suggestions? Perhaps there is some protection that prevents this, or its just not a concern?

You could implement IServiceCollection manually, defining a class, with a List<ServiceDescriptor> to implement all methods declared in the interfaces.
Then, modify the methods that may change the values of the items which are registries, adding notifying operations to determine whether the values are changed.

Related

Interface segregation principle for a framework interface with optional features

I am designing a authentication framework. I need users of the framework to implement data access logic since it is not the main purpose of the framework and I want to allow multiple data access approaches (SQL, NoSQL, Cache etc.) I don't implement it inside my framework. My framework uses this logic through an interface called IUserStore but the problem is, there are certain methods inside my interface that are used only when certain feature is active and not used otherwise. For example framework will try to access two factor information through GetTwoFactorInfo method only if two factor authentication is enabled.
My question is about interface segregation principle. Is it ok to leave the interface as it is and explain in the documentation that user needs to implement GetTwoFactorInfo only if user wants to use two factor authentication and throw NotImplementedException otherwise? Or should I separate interface for each optional feature and explain in the documentation user should implement and register this interface to service provider to be able to use that feature? A problem with second approach is when injecting services that implement those interfaces to constructors, I need to check if those features are active otherwise I would get an error because service is not registered and I am trying to access those services from service provider. Which leads to extra complexity for my framework classes.
What would be the best way to handle this problem?
There are practical problems with both of the approaches you suggest, but the plan to have clients throw NotImplementedException is far worse.
Let's go through both of them:
Option 1
leave the interface as it is and explain in the documentation that user needs to implement GetTwoFactorInfo only if user wants to use two factor authentication and throw NotImplementedException otherwise
Well, this might work for the problem you have today, but software design is about the problems you'll have tomorrow. What happens if you add support for different authentication methods to future versions of the framework? If you follow this pattern, then you'll add new methods to IUserStore... but this would break existing clients, because they will not have implemented them!
You can get around this particular problem in some languages by providing default implementations for new methods that throw exceptions, but that defeats much of the purpose of defining an interface in the first place -- the type system no longer tells the client what he has to implement.
Also, this pattern only works for pre-existing interfaces. If you add a new authentication method that requires the client to implement a new interface, that you're back to considering something like your second option, and then you'll have an inconsistent mix if versioning strategies. Ick.
Option 2
separate interface for each optional feature and explain in the documentation user should implement and register this interface to service provider to be able to use that feature
This is much better, but also not great, because it introduces hidden rules that clients of your framework have to follow. All of the ways to find out about these rules are frustrating -- read docs, troubleshoot errors, etc.
This is a common problem in lots of dependency injection systems, though, and lots of people don't seem to mind, but things get really complicated as interacting system of hidden rules accumulates.
Option 3
I don't know how you enable this 2-factor feature right now, but I would suggest that you have your customers enable this feature by calling a method that takes the implied dependencies as arguments, like
void enable2FactorAuth(I2FactorInfoStore store)
Then all the hidden rules go away. Your system ensures that you can't enable the feature unless you've implemented the required interfaces. Easy.
If you are thinking that you will lose the ability to configure your product without programming, then I would like to remind you that you do not have that feature. As you said, there is code that clients have to write in order to use 2 factor authentication. They have to implement the store. Requiring them to call a method to enable it will only improve this code, because it will now be obvious why they had to implement that store in the first place.

Can Castle Windsor be used to implement IDependencyResolver in ASP.NET MVC 4?

I read this article and saw many people commented that do not use Castle Windsor to implement IDependencyResolver in ASP.NET MVC3 and stick with a custom IControllerFactory. Basically my questions now are:
Do not use Castle Windsor to implement IDependencyResolver. Is this still true in ASP.NET MVC 4 ?
If 1 is the case. Can any other DI container (Unity, StructureMap) has the same problem as Castle Windsor? Can I use any alternative?
Thanks a lot
EDIT
Sounds to me that Castle Windsor should NOT be used to implement IDependencyResolver. I have decided to use some other DI container, such as StructureMap
There is no difference between MVC3 and MVC4 in regards to IDependencyResolver, other than the fact there is a separate resolver for WebAPI.
In my opinion, Mike Hadlow is a bit too caustic on this subject, and many other people have jumped on the bandwagon without truly considering why.
Yes, it's true that Castle Windsor has a specific object lifestyle (ie lifetime management object) called Pooled that often requires you to call Release on it. And when using this lifestyle, you should probably not use IDependencyResolver because it does not provide access to this Release method (although there are ways around that too).
However, I feel it's generally bad to use this lifestyle in a web application, and you should instead use the PerWebRequest lifestyle, which will automatically release objects at the end of the web request. If this is what you are using, then there is no problem with using IDependencyResolver with Castle Windsor.
Why do I think Hadlow is too caustic? Well, because he bases his entire argument on this:
"That’s right, no ‘Release’ method. You can provide a service from your IoC container, but there’s no way to clean it up. If I was going to use this in Suteki Shop, I would have a memory leak of epic proportions."
He then goes on to reference Krzysztof Koźmic's article regarding lifestyle management, but neglects to reference his followup article which I will do here:
http://kozmic.net/2010/08/27/must-i-release-everything-when-using-windsor/
Note what he says here:
"Since as I men­tioned in my pre­vi­ous post, Wind­sor will track your com­po­nent, it’s a com­mon mis­con­cep­tion held by users that in order to prop­erly release all com­po­nents they must call Release method on the container."
He goes on to talk about various other aspects as well, but in general, I don't think most people will be using Pooled or Transient objects that required disposal in a web application. And if you do, then you should know not to use IDependencyResolver then. Otherwise, you should have no problems.
I know I will probably get a lot of grief from people arguing otherwise, but I simply do not see this as the end of the world issue that people like Hadlow seem to think it is, since there are so many alternatives, and workarounds even when you do need to call Release.
Besides all this, using a lifestyle that requires calling Release means extra work for you, the developer. You now have to manage the object lifetimes and remember to dispose of objects, and failing to do so creates memory leaks. This is, essentially, nullifying the benefits of garbage collection in my opinion. I only ever use transient objects with things that do not need disposal, and I never use pooled objects.
By the way, I may be wrong, but I don't think any other container has this problem. This leads me to the conclusion that it's Windsor that is broken, rather than MVC, when every other container out there seems to not have an issue with this. Windsor likes to stubbornly hang on to its version of reality though, so YMMV.
The advice not to use IDependencyResolver is silly, because it can be used with Castle Windsor, even though the interface lacks a release method. The solution is simply to let the IDependencyResolver implementation cache each requested instance (in a cache bounded to the web request, using HttpContext.Items for instance). At the end of the web request all cached instances (usually just a few) can be released.
To be able to release all instances at the end of the web request, you should either register an Request_Ends event in the global.asax or register a HttpModule that does this.
You can call this a workaround, but not using the IDependencyResolver is not really an option, since it is too deeply integrated with MVC. Besides, other containers (such as Ninject and Simple Injector) use this same approach (using an HttpModule) to 'release' instances.
It's unfortunate though, that there isn't an official NuGet packages for omtegrating Windsor with MVC, since now you'll have to implement this yourself. All other frameworks do have such package btw. But again, it isn't that hard to implement this yourself.
Other IoC containers already show that it is possible to implement release as an implementation detail and you don't need Release as part of the IDependencyResolver contract. The MVC designers actually did the right thing by removing such method from the API.
While I agree implementing IDependencyResolver is possible and not terribly difficult.. and yes, depending on the lifestyles at play, explicitly Release()'ing may not matter... and yes, there are ways to force a Release() by caching the instance somewhere as well as other subtle tricks - I think this is alot to leave to interpretation and can be problematic and hard to track down. Understanding when Windsor is going to track an instance isn't always immediately obvious (i.e. if the component has decommission concerns vs. not, lifestyle, etc.). One of the core value-add's of IoC is to centralize the responsibility of object creation and instance management. To properly do that and have separation of concerns - you need to have an architecture that you can trust will serve you well in call scenarios and that IMO means having a iron clad answer for Release()'ing instance of all flavors. My advice is to always implement a design that will allow Release to be called - especially on roots (i.e. a Controller).
The final argument against IDependencyResolver is you have to register a number of MVC system components if you integrate at this level. That's too intimate of a dance between my app and the framework beneath it for my taste. IControllerFactory gives a much more targeted integration point, you don't have to register MVC system components and you get a Release() hook. So, unless you want to override MVC System components, I see very little reason to implement IDepedencyResolver over IControllerFactory. I see the opposite argument in fact. I personally wised up to this on this thread over here which shows both approaches.
Hope this helps

Ninject WCF: Attribute Injection

I am using the Ninject WCF extension project to do dependency injection on my web service. If I add an attribute to my web service (such as a an IServiceBehavior), how can I inject dependencies into that attribute when it is created at runtime?
Attributes are created by the .NET Runtime. Therefore there is no real dependency injection for them. You should try to avoid having attributes that require dependencies whenever possible. You have the following options:
Service behaviors can be added without attributes. But this requires that you extend the current WCF Extension with some way to define that you want to add a service behavior for some instances in a similar way as it is currently possible for MVC Filters. This is done here: https://github.com/ninject/ninject.extensions.wcf/blob/master/src/Ninject.Extensions.Wcf/ServiceHost/NinjectServiceHost.cs
You can implement an IInstance provider which searches your attributes and injects them. See https://github.com/ninject/ninject.extensions.wcf/blob/master/src/Ninject.Extensions.Wcf/NinjectInstanceProvider.cs
I'd try to go with the first option.
I disagree that attributes should not have dependencies in them. Often times validation attributes will have unavoidable dependencies. Attributes are an excellent example of DRY when used correctly.
The approach #wllmsaccnt took is essentially the KernelContainer approach which was removed in 2.2 - but worse. Now the attribute is coupled to the WCF app.
IMO this is precisely the reason I disagree with the removal of the KernelContainer. I'd definitely prefer injection over service locator, but I really don't see why service locator is discouraged when you are working within systems that you can't change or control.
It's surely better than writing additional custom code - for every application - that is most likely less maintainable and less testable than ServiceLocator.

Converting a Library to WCF web service

As the subject line describes, I am in the process of exposing a C# library into a WCF Service. Eventually we want to expose all the functionality, but at present the scope is limited to a subset of the library API. One of the goals of this exercise is also to make sure that the WCF service uses a Request / Response message exchange pattern. So the interface /API will change as the existing library does not use this pattern
I have started off by implementing the Service Contracts and the Request/Response objects, but when it comes to designing the DataContracts, I am not sure which way to go.
I am split between going back and annotating the existing library classes with DataContract/DataMember attributes VS defining new classes which are like surrogate classes to the existing classes.
Does anyone have any experience with similar task or have any recommendations on which way works best ? I would like to point out that our team owns the existing library so do have the source code for it. Any pointers or best practices will be helpful
My recommendation is to use the Adapter pattern, which in this case basically means create brand new DataContracts and ServiceContracts. This will allow everything to vary independently, and will allow you to optimize the WCF stuff for WCF and the API stuff for the API (if that makes sense). The last thing you want is to go down the modification route and find that something just won't map right once you are almost done.
Starting from .NET 3.5 SP1 you no longer need to decorate objects that you want to expose with [DataContract]/[DataMember] attributes. All public properties will be automatically exposed. This being said personally I prefer to use special DTO objects that I expose and decorate with those attributes. I then use AutoMapper to map between the actual domain models and the objects I want to expose.
If you are going to continue to use the existing library but want to have control over what you expose as the web service API, I would recommend defining new classes as wrapper(s) around the library.
What I mean to say is don't "convert" the existing library even if you think you're not going to continue to use it in other contexts. If it has been tested and proven, then take advantage of that fact and wrap around it.

Implementing repositories using NHibernate and Spring.Net

I'm trying to get to grips with NHibernate, Fluent NHibernate and Spring.
Following domain-driven design principals, I'm writing a standard tiered web application composed of:
a presentation tier (ASP.Net)
a business tier, comprising:
an application tier (basically a set of methods made visible to UI tier)
repository interfaces and domain components (used by the application tier)
A persistence tier (basically the implementation of the repository interfaces defined in the business tier)
I would like help determining a way of instantiating an NHibernate ISession in such a way that it can be shared by multiple repositories over the lifetime of a single request to the business tier. Specifically, I would like to:
allow the ISession instance and any transaction to be controlled outwith the repository implementation (perhaps by some aspect of the IOC framework, an interceptor?)
allow the ISession instance to be available to the repositories in a test-friendly manner (perhaps via injection or trough some shared 'context' abstraction)
avoid any unnecessary transactions being created (i.e. when only read-only operations have been executed)
allow me to write tests that use SQLLite
allow me to use Fluent NHibernate
allow the repository implementation to remain ignorant of the host environment. I don't yet know if the businese tier will run in-process with the presentation tier or will be hosted separately under WCF (in IIS), so I don't want to bind my code too closely to a HTTP context (for example).
My first attempt to solve this problem had been using the Registry pattern; storing the ISession instance in a ThreadStatic property. However, subsequent reading has suggested that isn't the best solution (as ASP.Net can switch the thread within the page lifecycle, I believe).
Any thoughts, part solutions, pattern names, pointers to up-to-date samples (NHibernate 2) will be most gratefully received.
I have not used Spring.NET so I can't comment on that. However, the rest sounds remarkably (or perhaps not so remarkably; we're hardly the first to implement these things ;) similar to my own experience. I too had trouble finding a One True Best Practice so I just read as much as I could and came up with my own interpretation.
In my situation I wanted transaction/session management to be external to the repository as well as keep repository concerns from bubbling up out of them (i.e. the code using the repository should not need to know that it's using NHibernate internally and shouldn't need to know anything about NHibernate session management). In my case it was decided that transactions would be created by default lest developers forget them, so I had to have a read-only escape mechanism. I went with the Unit of Work pattern with the NHibernate ISession instance store inside. Calling code (I also created a DSL interface for the UoW) might look something like:
using (var uow = UoW.Start().ReadOnly().WithHttpContext()
.InNewScope().WithScopeContext(ScopeContextProvider.For<CRMModel>())
{
// Repository access
}
In practice, that could be as short as UoW.Start() depending on how much context is already available. The HttpContext part refers to the storage location for the UoW which is, unsurprisingly, the HttpContext in this case. As you mentioned, for a ASP .NET application, HttpContext is the safest place to store things. ScopeContextProvider basically makes sure the right data context is provided for the UoW (ISession instance to the appropriate database/server, other settings). The "ScopeContext" concept also makes it easy to insert a "test" scope context.
Going this route makes the repositories explicitly dependent on the UoW interface. Actually, you might be able to abstract it some but I'm not sure I see the benefit. What I mean is, each repository method retrieves the current UoW instance and then pulls out the ISession object (or simply a SqlConnection for those methods that don't use NHibernate) to run the NHibernate query/operation. This works for me though because it also seems like the ideal time to make sure that the current UoW is not read-only for methods that might need to run CRUD.
Overall, I think this is one approach that solves all your points:
Allows session management to be external to the repository
ISession context can be mocked or pointed at a context provider for a test environment
Avoids unnecessary transactions (well, you'd have to invert what I did and have a .Transactional() call or something)
I can't see why you couldn't test with SQLite since that's more of an NHibernate concern
I use Fluent NHibernate myself
Allows the repository to be ignorant of the host environment (that is, the repository caller controls the UoW storage context)
As for the UoW implementation, I'm partially kicking myself for not looking around more before I started. There's a project called machine.uow which I understand is fairly popular and works well with NHibernate. I haven't played with it much so I can't say if it solves all my requirements as neatly as the one I wrote myself, but it might have saved development time as well.
Perhaps we'll get some comments as to where I went wrong or how to improve things, but I hope this is at least helpful in some way.
For reference, the software stack I'm using is:
ASP.NET MVC
Fluent NHibernate on top of NHibernate
Ninject for dependency injection
What you are describing is supported by the Spring.NET framework almost out of the box. Only for FluentNHibernate you need to add a custom SessionFactory (not a lot of code, look here:Using Fluent NHibernate in Spring.NET) to Spring.NET.
Every repository can use the same ISession, just inject the SessionFactory in your repositories and use Spring.NET's transaction services.
Just try it out, they have pretty thorough documentation imho.