Handling security and be decoupled - asp.net

I am trying to design an application in 3 layers :
1) Data access layer
2) business layer
3) UI
I try to keep classes decoupled so on the business layer I have created interfaces for the Data access classes like this :
public interface ICountryRepository:IRepository
{
Country GetCountry(int ID);
int CreateCountry(Country obj);
Boolean UpdateCountry(Country obj);
Boolean DeleteCountry(Country obj);
...
...
}
and i pass the interface as param to the service constructor :
public CountryService(ICountryRepository repository,ILanguageRepository lang_repository)
{
....
}
But on the CountryService for example I need to load the current user and his permissions so I can check if the operation can be applied :
public Country GetCountry(int ID)
{
if securityService.UserHasPermission(currentUser, GetPermission("CanGetCountry"))
{
return repository.GetCountry(ID);
}
else
{
Throw(New SecurityException("No permissions for that operation ...."))
}
}
That means I have to instantiate the SecurityDataAccess object and pass it to the constructor of the SecurityService on my business layer assembly which I try to avoid for keeping objects decoupled. Right now I even don't have a reference to any DataAccess assembly on my business assembly.
I am thinking of using an IoC container here. Using external configuration I could get the right class/assembly from a config file. But I am not sure that is the right solution because it is said that IoC containers should be used in one place to keep things simple and it should be the top level assembly (the UI assembly) most of the time.
Anybody has a suggestion for solving this problem ?

Why not add the security service into the constructor of the Country service? That way the IOC Container could resolve the dependency and inject the security if it is needed. That mean the IOC Container would take care of constructing your CountryService object. And you would use the container to get all Services.
Another option could be to "normalize" your repository a bit...
Trim it down to it only has 4-5 basic functions that are identical for all repositories, then use generics to make them all look alike, so no
UpdateCountry(...)
but
Update(T object)
Something like this:
http://codebetter.com/blogs/gregyoung/archive/2009/01/16/ddd-the-generic-repository.aspx
Then you can use a Chain of reponsibilty pattern to place your security code before the DB Code ( http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern )
So you could have a SecurityChecker that validates access, throws an exception if invalid, or passes down the request in the next link in the chain (You can also add a logging dynamically that way, or timing or whatever)

Do you need to implement security in the Data Access layer? If you move your security service to the business layer as Heiko suggests. In other words, perform security in the business layer and you avoid the IoC issue altogether.

This may be off-beam, apologies if it is, I'm a lurking Java EE programmer. It seems to me that authorisation is of methods is better addressed in the infrastructure, declaratively.
This article appears to suggest that .Net, like Java EE offers a facility to control access declaratively. Does this approach work for you?

Related

Dependency injection using PRISM Xamarin Forms doesn't work

I have a problem with dependency injection in my project. I use PRISM framework in my project and I chose Ioc container when create it. Link -> https://github.com/blackpantific/InstagroomEX
In my app.xaml file I associate the class and interface
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation<WelcomeView, WelcomeViewModel>();
containerRegistry.RegisterForNavigation<RegistrationView, RegistrationViewModel>();
containerRegistry.RegisterForNavigation<LoginView, LoginViewModel>();
//regestering
containerRegistry.RegisterSingleton<IValidationService, ValidationService>();
}
But my page after initializing() doesn't appear at the screen. This is ViewModel constructor
public RegistrationViewModel(INavigationService navigationService, IUserDataService userDataService,
IValidationService validationService) :
base(navigationService)
{
_userDataService = userDataService;
_validationService = validationService;
}
Something wrong here. When I pass to the RegistrationViewModel() constructor another parameters besides INavigationService navigationService the RegistrationView page doesn't not displayed. What am I doing wrong?
Assuming that WelcomePage is displayed correctly and RegistrationPage is not, I think that Andres Castro is correct: Prism tries to resolve the IUserDataService which is not possible. In the debug output you should see a message that IUserDataService cannot be resolved.
(Note: The following is based on my experiences with Prism and Unity. This might hold for other Dependency Injection frameworks, but it's possible that other frameworks behave differently.)
Prism relies on a Dependency Injection (DI) framework, for example Microsofts Unity application block. What happens when you try to navigate to RegistrationPage is, that Prism (if you are using ViewModelLocator.AutowireViewModel="True") tries to determine the type of the viewmodel (by convention) and asks the underlying DI framework to resolve this type (i.e. create an instance). For each of the required constructors parameters of this type, then again the DI framework tries to resolve them. If the parameters require concrete types it will then try to resolve those. If the parametery require interface (or abstract) types, the DI framework will look at its registrations and if the types have been registered create instances according to this registrations (which in turn might involve resolving other types).
If - however - the parameter requires an interface type which has not been registered, the DI framework does not know how to handle the situation. It coulld of course assume null, but this might lead to errors that might be way harder to track down, hence it will throw an exception (which is swallowed and Logged by Prism).
Now how can you handle the situation?
You'll need to tell the DI framework how to resolve IUserDataInterface. Since RegistrationPageViewModel does not actually use it, you could register null
containerRegistry.RegisterInstance<IValidationService>(null);
Could be irritating later, though. I'd rather remove the dependency of RegistrationPageViewModel to IUserDataService altogether - for now and add it later when it's actually used - or create a mock/stub that implements IUserDataService and is used as long there is no real implementation. This would be registered with the DI framework as you did with IValidationService.

ASP.Net MVC 6: Recursive Dependency Injection

Still exploring the new ASP.NET MVC5, now with build in DI!
No Problem so far, I can just inject my Handlers (I don't like the Term Service, since this defines to me a Platform-Neutral Interface):
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<Model.Meta.AppSettings>(Configuration.GetSection("AppSettings"));
services.AddSingleton(typeof(Logic.UserEndPointConfigurationHandler));
services.AddSingleton(typeof(Logic.NetworkHandler));
services.AddMvc();
}
Works fine, also the strongly typed Configuration-Object "AppSettings" works perfectly fine.
Also the Injection in the Controllers works as well.
But now my collaps: I seperated my DataAccess from the Handlers, and obviously I'd like to inject them as well:
public class UserEndPointConfigurationHandler
{
private readonly DataAccess.UserEndPointAccess _access;
public UserEndPointConfigurationHandler(DataAccess.UserEndPointAccess access)
{
_access = access;
}
But bam, UserEndPointAccess can't be resolved. So it seems like even I directly request to DI an Class with a Parameterless-Constructor, I need to register that. For this case, sure I should Interface and register them, but what does that mean for internal helper classes I also inject?
According to the Docs: http://docs.asp.net/en/latest/fundamentals/dependency-injection.html#recommendations and also the examples I found, all people in the world only seem to communicate between Controllers and some Repositories. No Business-Layer and no Classes on different Abstraction-Levels in Assemblies.
Is the Microsoft DI approach something totally differnt than the good ol' Unity one, where I can really decouple as fine granular as I'd like to?
Thanks in advance.
Matthias
Edit #Nightowl: I add my answer here, since it's a bit longer.
First of all, Unity does automatically create Instances, if I request a conecrete Type. This allows me to inject Types I register and Types, like Helper classes etc. I don't need to. This combination allows me to use DI everywhere.
Also in your Example I'd need to know the DataAcces in the WebGui, which is quite thight coupled. Well, I know there are solutions for this via Reflection, but I hoped Microsoft did something in this Topic, but probably that'd mean to big of a change.
Also allows Unity to store Instances or Instructions how to create them, another huge feature, which is missing at the moment.
Probably I'm just to spoiled, what refined DI-Libraries do, probably they also do to much, but at the moment the Microsoft-Implementation is just a huge downgrade according to my Information.
MVC Core follows the the composition root pattern, which is where object graphs are created based off of a set of instructions to instantiate them. I think you are misinterpreting what the IServiceCollection is for. It does not store instances, it stores instructions on how to create instances. The instances aren't actually created until a constructor somewhere in the object graph requests one as a constructor parameter.
So, in short the reason why your service (which you call UserEndPointAccess) is not being instantiated when you request it is because you have not configured the IServiceCollection with instructions on how to create it.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<Model.Meta.AppSettings>(Configuration.GetSection("AppSettings"));
services.AddSingleton(typeof(Logic.UserEndPointConfigurationHandler));
services.AddSingleton(typeof(Logic.NetworkHandler));
// Need a way to instantiate UserEndPointAccess via DI.
services.AddSingleton(typeof(DataAccess.UserEndPointAccess));
services.AddMvc();
}
So it seems like even I directly request to DI an Class with a Parameterless-Constructor, I need to register that.
If you are doing DI correctly, each service class will only have a single constructor. If you have more than one it is known as the bastard injection anti-pattern, which essentially means you are tightly coupling your class definition to other classes by adding references to them as foreign defaults.
And yes, you need to register every type you require (that is not part of MVC's default registration). It is like that in Unity as well.

C#/ASP.NET MVC 4 Instantiate Object Derived From Interface In Factory Method

Currently have a Factory class that features a GetSelector function, which returns a concrete implementation of ISelector. I have several different classes that implement ISelector and based on a setting I would like to receive the appropriate ISelector back.
public interface ISelector
{
string GetValue(string Params);
}
public class XmlSelector : ISelector
{
public string GetValue(string Params)
{
// open XML file and get value
}
}
public static class SelectorFactory
{
public static ISelector GetSelector()
{
return new XmlSelector(); // Needs changing to look at settings
}
}
My question is what is the best way to store the setting? I am aware of using AppSettings etc. but I'm not sure whether I want to have to store strings in the web.config and perform a switch on it - just seems to be really tightly coupled in that if a new implementation of ISelector is made, then the Factory would need to be changed. Is there any way of perhaps storing an assembly name and instantiating based on that?
Thanks,
Chris
It is hard to say, because I don't know the architecture of your particular project, but at a first glance what I would do is if the objects associated with ISelector can be decoupled from your web application, I would put these objects in a class library along with the factory. Your factory will need to be changed if you implement a new ISelector, but if you can decouple the whole ISelector family from your actual web application the depth of the refactoring you will have to do will be minimal compared to a monolithic architecture.
Personally, I tend to avoid AppSettings, web.config settings and the like for mission-critical design questions. Using the web.config as an example, I have seen applications where architectural data is stored for ease of configurability. The problem is that after compilation your web.config can be changed (that is the purpose of it after all) and if the implementation of your classes depends on very specific values being chosen, you are running a risk of a crash when someone inadvertently modifies the wrong value.
Like I said all this depends entirely on your application architecture, but my reflex would be to split out the components that could be subject to future modification into a class library. Loose coupling is your friend ;).
Instead of doing it in AppSettings, I think a better approach will be to create a separate XML file, which will only hold the mappings and from that file you can iterate through the mappings and return correct instance in GetSelector().

Why would I want to use UnitOfWork with Repository Pattern?

I've seen a lot about UnitOfWork and Repo Pattern on the web but still don't have a clear understanding of why and when to use -- its somewhat confusing to me.
Considering I can make my repositories testable by using DI thru the use of an IoC as suggested in this post What are best practices for managing DataContext. I'm considering passing in a context as a dependency on my repository constructor then disposing of it like so?:
public interface ICustomObjectContext : IDisposable {}
public IRepository<T> // Not sure if I need to reference IDisposable here
public IMyRepository : IRepository<MyRepository> {}
public class MyRepository : IMyRepository
{
private readonly ICustomObjectContext _customObjectContext;
public MyRepository(ICustomObjectContext customObjectContext)
{
_customObjectContext = customObjectContext;
}
public void Dispose()
{
if (_customObjectContext != null)
{
_customObjectContext.Dispose();
}
}
...
}
My current understanding of using UnitOfWork with Repository Pattern, is to perform an operation across multiple repositories -- this behavior seems to contradict what #Ladislav Mrnka recommends for web applications:
For web applications use single context per request. For web services use single context per call. In WinForms or WPF application use single context per form or per presenter. There can be some special requirements which will not allow to use this approach but in most situation this is enough.
See the full answer here
If I understand him correctly the DataContext should be shortlived and used on a per request or presenter basis (seen this in other posts as well). In this case it would be appropriate for the repo to perform operations against the context since the scope is limited to the component using it -- right?
My repos are registered in the IoC as transient, so I should get a new one with each request. If that's correct, then I should be getting a new context (with code above) with each request as well and then disposing of it -- that said...Why would I use the UnitOfWork Pattern with the Repository Pattern if I'm following the convention above?
As far as I understand the Unit of Work pattern doesn't necessarily cover multiple contexts. It just encapsulates a single operation or -- well -- unit of work, similar to a transaction.
Creating your context basically starts a Unit of Work; calling DbContext.SaveChanges() finishes it.
I'd even go so far as to say that in its current implementation Entity Framework's DbContext / ObjectContext resembles both the repository pattern and the unit of work pattern.
I would use a simplified UoW if i wanted to push context's SaveChanges away from the repositories when they share the same instance of context across one web request.
I imagine you have sth like Save() method on your repositories that looks similiar to _customObjectContext.SaveChanges(). Now lets assume you have two methods containing business logic and using repos to persist changes in DB. For the sake of simplicity we'll call them MethodA and MethodB, both of them containing a fair amount of logic for performing some activities. MethodA is used separately in the system but also it is called by MethodB for some reason. What happens is MethodA saves changes on some repository and since we are still in the same request changes made in MethodB, before it called MethodA, will also be saved regardless of whether we want it or not. So in such case we unintentionally break the transaction inside MethodB and make the code harder to understand.
I hope i described this clear enough, it wasn't easy. Anyway other than that i cannot see why UoW would be helpful in your scenario. As Dennis Traub pointed quite correctly ObjectContext and DbContext are in fact an implementation of a UoW so you'd be probably reinventing the wheel while implementing it on your own.
The ObjectContext/DbContext is an implementation of the UnitOfWork pattern. It encapsulates several operations and makes sure they are submitted in one transaction to the database.
The only thing you are doing is wrapping it in your own class to make sure you're not depending on a specific implementation in the rest of your code.
In your case, the problem lies in the fact that your Context shouldn't be disposed of by your Repository. The Repository is not the one that instantiates the Context, so it shouldn't dispose of it either. The UnitOfWork that encapsulates multiple repositories is responsible for creating and disposing the Context and you will call a Save method on your UnitOfWork.
Code can look like this:
using (IUnitOfWork unitOfWork = new UnitOfWork())
{
PersonRepository personRepository = new PersonRepository(unitOfWork);
var person = personRepository.FindById(personId);
ProductRepository productRepository = new ProductRepository(unitOfWork);
var product= productRepository.FindById(productId);
p.CreateOrder(orderId, product);
personRepository.Save();
}

Purpose of Unity Application Block in Microsoft Enterprise Library?

Can someone explain to me what is the purpose of the Unity Application Block? I tried looking through the documentation but its all very abstract.
What are some practical uses for the Unity block?
Inversion of Control
A quick summation (lot more reading is available this topic, and I highly suggest reading more)...
Microsoft's Unity from the Enterprise Patterns and Practices team is an Inversion of Control container project, or IoC for short. Just like Castle Windsor, StructureMap, etc. This type of development is also referred in lamen's terms as Loosely Coupling your components.
IoC includes a pattern for Dependency Injection of your objects, in which you rely on an external component to wire up the dependencies within your objects.
For example, instead of accessing static managers (which are near impossible to unit test), you create an object that relies on an external dependency to act upon. Let's take a Post service in which you want to access the DB to get a Post.
public class PostService : IPostService
{
private IPostRepository _postRepo;
public PostService(IPostRepository postRepo)
{
_postRepo = postRepo;
}
public IList<Post> GetPosts()
{
return _postRepo.GetAllPosts().ToList();
}
}
This PostService object now has an external dependency on IPostRepository. Notice how no concretes and no static manager classes are used? Instead, you have a loose-coupling of a simple Interface - which gives you the power of wiring up all different kinds of concrete classes that implement IPostRepository.
Microsoft Unity's purpose is to wire up that IPostRepository for you, automatically. So you never have to worry about doing:
// you never have to do this with Unity
IPostRepository repo = new PostRepository();
IPostService service = new PostService(repo); // dependency injection
IList<Post> posts = service.GetPosts();
The above shows where you have to implement two concrete classes, PostRepository() and PostService(). That is tightly-coupling your application to demand/require those exact instances, and leaves it very difficult to unit test.
Instead, you would use Unity in your end point (The controller in MVC, or code behind in ASPX pages):
IUnityContainer ioc = new UnityContainer();
IPostService postService = ioc.Resolve<IPostService>();
IList<Post> posts = postService.GetPosts();
Notice that there are no concretes used in this example (except UnityContainer and Post, obviously)! No concretes of the services, and no repository. That is loosely-coupling at its finest.
Here's the real kicker...
Unity (or any IoC container framework out there!) will inspect IPostService for any dependencies. It will see that it wants (depends) on an instance of IPostRepository. So, Unity will go into it's object map and look for the first object that implements IPostRepository that was registered with the container, and return it (i.e. a SqlPostRepository instance). That is the real power behind IoC frameworks - the power to inspect services and wire up any of the dependencies automatically.
I need to finish my blog post about the comparisons of UNity vs Castle vs StructureMap. I actually prefer Castle Windsor due to its configuration file options, and extensibility points personally.
The Unity Application Block is used for dependency injection. I think the best simple definition for DI is from this question
When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might even be looking for something we don't even have or which has expired.
What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat.
So for an example,
IUnityContainer container = new UnityContainer();
ILunch lunch = container.Resolve<ILunch>();
Console.WriteLine(lunch.Drink);
This Outputs "Lemonade" because we defined Drink as a Dependency.
public class ILunch {
[Dependency]
public IDrink Drink { get; set; }
}
As far as practicality goes, Dependency Injection is really great when you have Dependencies on other objects and you don't want the developer to have to manually set them. It is that simple. It is also great for mocking. The most used example I can think of that I use is mocking a data layer. Sometimes the database isn't ready so instead of stopping development I have a fake layer that returns fake data. The data object is accessed via DI and can be configured to return objects which access the fake layer or the real layer. In this example I am almost using the DI Container as a configurable factory class. For more on Unity MSDN has some great resources http://msdn.microsoft.com/en-us/library/cc468366.aspx.
Other good DI Frameworks include Spring.NET and Ninject

Resources