My current class PropertyManager looks like this:
public class PropertyManager : IDisposable
{
private readonly IPropertyRepo _propertyRepo;
private readonly IUserTypeRepo _userTypeRepo;
public PropertyManager(IPropertyRepo propertyRepo, IUserTypeRepo userTypeRepo = null)
{
if (propertyRepo == null)
throw new ArgumentNullException("propertyRepo");
_propertyRepo = propertyRepo;
if (userTypeRepo != null)
_userTypeRepo = userTypeRepo;
}
}
My Property Manager will use the _userTypeRepo in some method to accomplish some task. I think I want to implment a rule that says "Each Manager(Service,Factory,etc) should be responsible for its own repository."
The idea:
The PropertyManager, because it needs to do something with the UserTypeRepo, I should be using the UserManager for such activities.
As such, this means that I will not provide a repo when creating an instance of the UserManager (i.e., var usrMgr = new UserManager(); // no repo). Instead, the UserManager will use the default constructor which will create a new instance of the IUserTypeRepo and provide a new instance of a UserManager and then it can do its work.
I think this accomplishes some design principle such as Separation of Concerns and the Single Responsibility, but then I may be getting away from my Dependency Injection design pattern as the new Managers would now have multiple constructors and look like this:
public class PropertyManager : IDisposable
{
private readonly IPropertyRepo _propertyRepo;
public PropertyManager(){
// use the default repo
_propertyRepo = new PropertyRepo();
}
// Used from Controller or Unit Testing
public PropertyManager(IPropertyRepo propertyRepo)
{
if (propertyRepo == null)
throw new ArgumentNullException("propertyRepo");
}
}
public class UserManager : IDisposable
{
private readonly IUserRepo _userRepo;
public UserManager(){
// use the default repo
_userRepo = new UserRepo();
}
// Used from Controller or Unit Testing
public UserManager(IUserRepo userRepo)
{
if (userRepo == null)
throw new ArgumentNullException("userRepo");
}
}
Would this be frowned upon? Or am I on the right track? In either case, why and thanks?
Update. After reading Yawar's post I decided to update my post and I think I have a relevant concern.
Let's think of a real world example of the above. I have a PropertyManager in real life named "Robert" one of the jobs he performs each morning at work is to Open() the Property (i.e., he unlocks the Property he is the Manager of). I also have a UserManger who manages people who visit the Property and her name is "Sarah" she has a function that she does called EnterProperty() (which is what she does in the morning when she physically walks into the building).
Rule: UserManager has a dependency on PropertyManager when using the EnterProperty()
This looks like this according to all accepted standards:
Property Manager
class PropertyManager : IPropertyManager
{
private readonly IPropertyRepo _propertyRepo;
public PropertyManager(IPropertyRepo propertyRepo)
{
if (propertyRepo == null)
throw new ArgumentNullException("propertyRepo");
this._propertyRepo = propertyRepo;
}
// this is when Robert opens the property in the morning
public void Open()
{
_propertyRepo.Open();
}
// this is when Robert closes the property in the evening
public void Close()
{
_propertyRepo.Close();
}
// this answers the question
public bool IsOpen()
{
return _propertyRepo.IsOpen();
}
}
User Manager
class UserManager : IUserManager
{
private readonly IPropertyRepo _propertyRepo;
private readonly IUserRepo _userRepo;
public UserManager(IUserRepo userRepo, IPropertyRepo propertyRepo = null)
{
if (userRepo == null)
throw new ArgumentNullException("userRepo");
this._userRepo = userRepo;
if (propertyRepo != null)
this._propertyRepo = propertyRepo;
}
// this allows Sarah to physically enter the building
public void EnterProperty()
{
if(_propertyRepo.IsOpen())
{
Console.WriteLine("I'm in the building.");
}else{
_propertyRepo.Open(); // here is my issue (explain below)
Console.WriteLine("Even though I had to execute the Open() operation, I'm in the building. Hmm...");
}
}
}
Web API Controller
{
public void OpenForBusiness(){
private const IPropertyRepo propertyRepo = new PropertyRepo();
private IPropertyManager propertyManager = new PropertyManager(propertyRepo);
private IUserManager userManager = new UserManager(new UserRepo(), propertyRepo);
// Robert, the `PropertyManager`, opens the `Property` in the morning
propertyManager.Open();
// Sarah, the `UserManager`, goes into `Property` after it is opened
userManager.EnterProperty();
}
}
Now, everything is cool and I can walk away and I now have a Repository Pattern which use Dependency Injection which supports TDD and not tightly coupled classes among other benefits.
However, is the truly realistic? (explain why I ask in second)
I think a more real-world (realistic) approach is one that does:
Web API Controller
public void Method1()
{
private IPropertyManager propMgr = new PropertyManager(new PropertyRepo());
private IUserManager userMgr = new UserManager(new UserRepo()); // no dependencies on any repository but my own
// 1. Robert, the `PropertyManager`, opens the `Property`
propMgr.Open();
// 2. Check to see if `Property` is open before entering
// choice a. try to open the door of the `Property`
// choice b. call or text Robert, the `PropertyManager`, and ask him if he opened the `Property` yet, so...
if(propMgr.IsOpen()){
// 3. Sarah, the `UserManager`, arrives at work and enters the `Property`
userMgr.EnterProperty();
}else{
// sol, that sucks, I can't enter the `Property` until the authorized person - Robert - the `PropertyManager` opens it
// right???
}
}
the EnterProperty() method on the UserManager now looks like this:
// this allows Sarah to physically enter the building
public void EnterProperty()
{
Console.WriteLine("I'm in the building.");
}
The promised explanation from above:
If we think in real-world terms we must agree that the later is preferred over the former. When thinking of a Repository lets say this is the definition of ones self (i.e., one's Person) (i.e., the UserRepo having all the data related to the User, is to the UserManager as the DNA, Heartbeat, Brain Wave Pattern, etc. is to a Human (the HumanRepo). As such, allowing the UserManager to know about the PropertyRepo and having access to its Open() method violates all Real-World security principles and Business Rules. In reality this says that through My Contructor() I can get an Interface Representation of a PropertyRepo that I can use any way I see fit. This is synonymous to the following logic of the HumanRepo:
I, Sarah - a UserManager - through a new instance of myself with the satisfaction of the PropertyRepo through my Constructor() create a Hologram Interface of Robert, the PropertyManager that I can use any way I see fit. Granted right now I only want to use the IsOpen() method of the PropertyRepo I actually use the Open() method to do it myself if Robert has not yet performed his duty. This is a security concern to me. In the real-world this says I don't have to wait for Robert to open the Property and use the Holocopy of him and implement his Open() method to get access.
That doesn't seem right.
I think with the last implementation I get SoC, SRP, DI, Repository Pattern, TDD, and Logical Security and as close to a real-world implementation as possible.
What do you all think?
I think I agree with your SoC and breaking the PropertyManager class into PropertyManager and UserManager classes. You are almost there.
I would just refactor as shown below:
public class PropertyManager : IDisposable, IPropertyManager
{
private readonly IPropertyRepo _propertyRepo;
// Used from Controller or Unit Testing
public PropertyManager(IPropertyRepo propertyRepo)
{
if (propertyRepo == null)
throw new ArgumentNullException("propertyRepo");
this._propertyRepo = propertyRepo;
}
}
public class UserManager : IDisposable, IUserManager
{
private readonly IUserRepo _userRepo;
// Used from Controller or Unit Testing
public UserManager(IUserRepo userRepo)
{
if (userRepo == null)
throw new ArgumentNullException("userRepo");
this._userRepo = userRepo;
}
}
Note: Just extract IPropertyManager & IUserManager so that the calling classes will depend upon the interfaces and provide the implementation.
Creating parameterless constructor is useless if you want to (you should) force the client to provide the concrete implementation of IPropertyRepo and IUserRepo interfaces.
public PropertyManager(){
// use the default repo
_propertyRepo = new PropertyRepo();
}
I dont think you would need
if (propertyRepo == null)
throw new ArgumentNullException("propertyRepo");
or
if (userRepo == null)
throw new ArgumentNullException("userRepo");
as IPropertyRepo and IUserRepo will be resolved via a IoC at the startup of your application (say its MVC then before calling the controller IoC will resolve them) so no need to check for null. I have never checked the dependencies for null in my code.
From what you have posted here thats pretty much it.
Unit of Work pattern is used for repository layer not in the manager layer. I would delete that from the title.
Hope this helps!
I think this accomplishes some OOP goal such as Separating Concerns
and the Single Responsibility Principle.
The result is opposite. Now, PropertyManager tightly couples to PropertyRepo; previously, they were loosely coupled.
First approach is better than the latter one. However, PropertyManager and UserManager should not create other objects on which they rely to do their work. The responsibility for creating and managing object should be offloaded to IoC container.
Interfaces describe what can be done, whereas classes describe how it is done. Only classes involve the implementation details—interfaces are completely unaware of how something is accomplished. Because only classes have constructors, it follows that constructors are an implementation detail. An
interesting corollary to this is that, aside from a few exceptions, you can consider an appearance of the new keyword to be a code smell. - Gary McLean Hall
Answer for Updated Question:
In your updated question, you combine Service/Manager and somewhat Domain into a single class - PropertyManager, UserManager. It becomes personal preference.
I personally like to keep them separate. In addition, I like to use Role based and Claim based authorization. Let me use my GitHub sample project as a reference. Please feel free to clone it.
User Domain
User class is also used by Entity Framework Code First Fluent API.
public partial class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
}
User Service
public class UserService : IUserService
{
private readonly IRepository<User> _repository;
public UserService(IRepository<User> repository)
{
_repository = repository;
}
public async Task<IPagedList<User>> GetUsersAsync(UserPagedDataRequest request)
{
...
}
}
Action Method
Notice that UI related Business Logic stays at UI layer.
public async Task<ActionResult> Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
bool result = _activeDirectoryService.ValidateCredentials(
model.Domain, model.UserName, model.Password);
if (result)
{
...
}
}
...
}
you can take quite a bit of a different approach.....( ignoring your repositories, but allowing for it to be injected )
In this system, the property is only readable, with an event system to handle the mutations, the event system also has rules system which controls what mutations are allowed. This means even if you have a property object you can't mutate it without going through its rules.
This code is more conceptual. The next logical step is to use a full actor model and something like (akka.net) and you may find your repository pattern just disappearing :)
public class Property
{
public string Name { get; private set; }
private IPropertyRules _rules;
private List<User> _occupants = new List<User>();
private IEventLog _eventLog;
public Property(IPropertyRules rules, IEventLog eventLog)
{
_rules = rules;
_eventLog = eventLog;
}
public ActionResult Do(IAction action, User user)
{
_eventLog.Add(action, user);
if (_rules.UserAllowedTo(action, user, this))
{
switch (action)
{
case Open o:
Open();
return new ActionResult(true, $"{user} opened {Name}");
case Enter e:
Enter(user);
return new ActionResult(true, $"{user} entered {Name}");
}
return new ActionResult(false, $"{Name} does not know how to {action} for {user}");
}
return new ActionResult(false, $"{user} is not allowed to {action} {Name}");
}
private void Enter(User user)
{
_occupants.Add(user);
}
private void Open()
{
IsOpen = true;
}
public bool IsOpen { get; set; }
}
public interface IEventLog
{
void Add(IAction action, User user);
}
public class Enter : IAction
{
}
public interface IPropertyRules
{
bool UserAllowedTo(IAction action, User user, Property property);
}
public class Open : IAction
{
}
public class ActionResult
{
public ActionResult(bool successful, string why)
{
Successful = successful;
WhatHappened = why;
}
public bool Successful { get; private set; }
public string WhatHappened { get; private set; }
}
public interface IAction
{
}
public class User
{
}
Related
I am having a custom context class in my ASP.NET 4.8 Framework website:
public sealed class MyCustomContext
{
private static readonly Lazy<MyCustomContext> staticContext =
new Lazy<MyCustomContext>(() => new MyCustomContext());
private MyCustomContext()
{
}
public static MyCustomContext Current => staticContext.Value;
public HttpContext Context => HttpContext.Current;
// Logic to return current user based on logged in user
public User LoggedInUser => ...
// Logic to return SiteWideSettings
public Collection<SiteWideSettings> SiteWideSettings => ...
}
The above class is a Singleton and the usage of the above class in my service class methods is like this:
public class MyService : IMyService
{
public MyService()
{
}
public void DoWork()
{
var current = MyCustomContext.Current;
var loggedInUser = current.LoggedInUser;
var siteWideSettings = current.SiteWideSettings;
var currentContext = current.Context;
// use the above properties further for this method
}
}
My goal is to remove MyCustomContext class dependency hardcoded in my DoWork method of MyService class so that it can look like this:
public class MyService : IMyService
{
private readonly IMyCustomContext _myCustomContext;
public MyService(IMyCustomContext myCustomContext)
{
_myCustomContext = myCustomContext;
}
public void DoWork()
{
var current = _myCustomContext.Current;
var loggedInUser = current.LoggedInUser;
var siteWideSettings = current.SiteWideSettings;
var currentContext = current.Context;
// use the above properties further for this method
}
}
Can you share how to convert my MyCustomContext class so that it can be injected via dependency injection into MyService?
I have one more question, do the properties like LoggedInUser, SiteWideSettings and Context of MyCustomContext class should be written as properties or they should be converted to methods for dependency injection?
For the dependency injection you need an interface which gets initialized, so your MyCustomContext class needs to implement a new interface called IMyCustomContext. The interface can look like following:
public interface IMyCustomContext
{
HttpContext Context { get; }
User LoggedInUser { get; }
Collection<SiteWideSettings> SiteWideSettings { get; }
}
public class MyCustomContext : IMyCustomContext
{
public HttpContext Context
{
get { return HttpContext.Current; }
}
public User LoggedInUser
{
get
{
// Logic to return current user based on logged in user
}
}
public Collection<SiteWideSettings> SiteWideSettings
{
get
{
// Logic to return SiteWideSettings
}
}
}
In the Startup.cs there is a method called ConfigureServices, there you can add the following for the dependency injection:
container.RegisterType<IMyCustomContext, MyCustomContext>(
TypeLifetime.Singleton);
It's worth pointing out that Singleton has dual meaning here:
The Singleton Design Pattern ensures an object is only instantiated once. Its implementation isn't ideal though, as it relies on ambient state.
The Singleton Lifetime is used by IOC frameworks, where it ensures the same reference of an object is used every time.
In short, the Singleton Lifetime effectively removes the need to implement the Design Pattern, because the IOC framework ensures the backing concept for you.
Meaning, if we register our dependency with the Singleton Lifetime.
container.RegisterType<ICustomContext, MyCustomContext>(TypeLifetime.Singleton);
We can remove the code for the Singleton Pattern, as the IOC container will take over the responsibility of guarding the single instance/reference.
public class MyCustomContext : ICustomContext
{
public HttpContext Context => HttpContext.Current;
// Logic to return current user based on logged in user
public User LoggedInUser => ...
// Logic to return SiteWideSettings
public Collection<SiteWideSettings> SiteWideSettings => ...
}
I've also added the ICustomContext interface with the member we're interested in.
public interface ICustomContext
{
HttpContext Context { get; }
User LoggedInUser { get; }
Collection<SiteWideSettings> SiteWideSettings { get; }
}
Can you share how to moq properties of that class?
That's right, we just moved the problem one level, didn't we? If you need to extract an interface, you usually need to do this in a recursive manner.
This also means HttpContext is not a good candidate for an interface member, which makes sense when you think about it. From a unit test's point of view, we're not interested in verifying ASP.NET's inner workings. Instead, we want to check our own code, and only that portion, with no dependencies on foreign libraries. To do so, you should only copy the HttpContext members you need on to your interface and remove the dependency on HttpContext (which is notoriously hard to abstract).
For example:
public interface ICustomContext
{
IPrincipal User { get; }
User LoggedInUser { get; }
Collection<SiteWideSettings> SiteWideSettings { get; }
}
This will require some refactoring / remodeling as the number of properties grows.
For simple DTO's you can even choose not to abstract / interface them, as long as your able to easily create fakes for unit testing. Also remember it only makes sense to introduce an interface if there are going to be multiple implementations.
One more thing about Dependency Inversion, and how IOC frameworks work, you usually let the dependencies bubble up. The recommended approach is through constructor injection, as illustrated in the following ICustomContext implementation for unit tests.
public class TestCustomContext : ICustomContext
{
public MyCustomContext(IPrincipal user, User loggedInUser, Collection<SiteWideSettings> siteWideSettings)
{
User = user;
LoggedInUser = loggedInUser;
SiteWideSettings = siteWideSettings;
}
IPrincipal User { get; }
User LoggedInUser { get; }
Collection<SiteWideSettings> SiteWideSettings { get; }
}
I have one more question, do the properties like LoggedInUser, SiteWideSettings and Context of MyCustomContext class should be written as properties or they should be converted to methods for dependency injection?
You can have both. If the state was injected through constructor injection, you might as well expose it as a property. If the implementing class implements behavior to create / transform the state, you might want to expose the behavior as a method. It all depends on the actual case, there is no golden bullet here. Just remember that in OO design, interfaces are used to model behaviors, with their scope kept as small as possible.
UPDATE
Those properties are not getting filled via constructor. All of these properties "IPrincipal User { get; } User LoggedInUser { get; } Collection SiteWideSettings { get; }" have the body in their getter, they get the data from cache first and if not found then it calls the service to get the data from db for those properties (all that is written in in the get of those properties). Should I keep them as properties only or make them methods?
Let me split up your question.
Should I keep them as properties only or make them methods?
From a technical point of view, it doesn't really matter. Properties, or automated properties (like the ones you're using), are just syntactic sugar over full blown methods. Meaning, they all get compiled into equivalent CIL instructions.
That leaves only the human factor. The readability and maintainability of your code. The agreed upon coding style and practices. That's not something I can answer for you. Personally, I prefer methods for handling these kind of code flows.
they get the data from cache first and if not found then it calls the service to get the data from db for those properties (all that is written in in the get of those properties).
Sounds like this class is more of a service provider than an actual model class in your domain. As there's also I/O involved, I'd definitely recommend switching to asynchronous methods on your interface. The explicit (Task based) signature says a lot to fellow developers reading your code.
The part where I talked about the dependencies bubbling up plays an important role here. The cache and repository are both dependencies of MyCustomContext. IOC and its inherent Dependency Inversion Principle rely on the explicit declaration of dependencies, as shown in the following sample. Note the implementation of GetLoggedInUser() is not what matters here, rather the way the dependencies are set through the constructor. All these dependencies need to be registered with your IOC container first, for it to be able to resolve ICustomContext.
public class MyCustomContext : ICustomContext
{
private readonly IUsersCache _usersCache;
private readonly IUsersRepo _usersRepo;
public MyCustomContext(IUsersCache usersCache, IUsersRepo usersRepo, IPrincipal principal)
{
_usersCache = usersCache;
_usersRepo = usersRepo;
Principal = principal;
}
public IPrincipal Principal { get; }
public async Task<LoggedInUser> GetLoggedInUser()
{
var userId = await GetUserId(Principal);
var user = _usersCache.GetById(userId);
if (user == null)
{
user = _usersRepo.GetById(userId);
_usersCache.Add(user);
}
return user;
}
...
}
Those properties are not getting filled via constructor. All of these properties "IPrincipal User { get; } User LoggedInUser { get; } Collection SiteWideSettings { get; }" have the body in their getter
I don't think that's true for IPrincipal as it, together with HttpContext, is instantiated by ASP.NET behind the scenes. All you need to do is tell the IOC container how to resolve the current IPrincipal and let it work its magic.
Likewise, all classes that depend on ICustomContext should have it injected by the IOC container.
public class MyService : IMyService
{
private readonly ICustomContext _customContext;
public MyService(ICustomContext customContext)
{
_customContext = customContext;
}
public async Task DoWork()
{
var currentPrincipal = _customContext.Principal;
var loggedInUser = await _customContext.GetLoggedInUser();
...
}
}
An important part here is again unit testing. If you design your classes like this, you can easily create fakes for testing. And even if there wasn't any testing involved, which I wouldn't recommend, the ability to decouple classes like this is a good indication of a well designed code base.
I have a base controller and before every page load I want to get the current user. I originally had a constructor in my BaseController that looked like this
public BaseController(ISystemUserCommand command)
{
_systemUserCommand = command
}
The problem with this then is that every controller that inherits from the BaseController would have to contain the ISystemUserCommand in its constructor, which I don't think would be good.
Instead I tried to create just an instance of the service class (shown below - it's the commented line under var sid...) but I need to pass in user service. How would I pass in the user service here or is this a bad way of doing it?
public abstract class BaseController : Controller
{
public SystemUserViewModel CurrentUser { get; set; }
private readonly ISystemUserCommand _systemUserCommand;
public SystemUserViewModel GetCurrentUser()
{
if (HttpContext == null || HttpContext.User == null) return null;
if (CurrentUser != null) return CurrentUser;
var sid = System.Web.HttpContext.Current.Request.LogonUserIdentity.User.ToString();
//var command = new SystemUserCommand();
CurrentUser = _systemUserCommand.GetUser(sid);
return CurrentUser;
}
public void SetUserInformation(SystemUserViewModel currentUser)
{
ViewBag.UserId = currentUser.SystemUserId;
ViewBag.FullName = string.Format("{0} {1}", currentUser.FirstName, currentUser.LastName);
ViewBag.FirstName = currentUser.FirstName;
ViewBag.LastName = currentUser.LastName;
ViewBag.CurrentUser = currentUser;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var currentUser = GetCurrentUser();
if (currentUser != null)
{
if (currentUser.IsActive)
{
SetUserInformation(currentUser);
}
else
filterContext.Result = RedirectToAction("denied", "unauthorized");
}
else
filterContext.Result = RedirectToAction("denied", "unauthorized");
base.OnActionExecuting(filterContext);
}
}
public class SystemUserCommand : ISystemUserCommand
{
private readonly ISystemUserBusiness _systemUserBusiness;
public SystemUserCommand(ISystemUserBusiness systemUserBusiness)
{
_systemUserBusiness = systemUserBusiness;
}
...
}
You could use property injection instead of constructor injection, via the base class, eg using unity:
public abstract class BaseController : Controller
{
[Dependency]
public ISystemUserCommand SystemUserCommand { get; set; }
}
This would mean the interface reference is only on the base class.
See here for the full examples.
EDIT, Autofac example:
You don't need property attributes on the dependency,
public abstract class BaseController : Controller
{
public ISystemUserCommand SystemUserCommand { get; set; }
}
Just to register the properites to auto resolve on the autofac builder:
builder.RegisterControllers(typeof(MvcApplication).Assembly).Where(t => t.IsAssignableFrom(typeof(BaseController))).PropertiesAutowired();
See autofac property injection here.
First of all, it does not seem a good idea to have OnActionExecuting override in the controller. You can use filters, that are specially designed for this purpose. And it seems that is the main reason you created the BaseController at all.
Regarding the problem with injecting the system command in all the required service, I would do so, but without inheriting from a base class, since I generally prefer aggregation to inheritance. That would mean that each controller that needs to work with the service will get it.
Another option that I have used few times to abstract some operations is to create a UserSerivce that will provide the required operations to the controllers. It will have ISystemUserCommand and HttpContext injected inside so that all of your controllers won't have to do the job. You can either use HttpContext.Current as static or abstract it away if you need testability.
Moreover I would not recommend property injection since it is more obscure than constructor injection that should be preferred if possible.
You can read more about filters here. Unfortunately if you use filters it's not that easy to inject in filters themselves and mostly done with property injection or ServiceLocator pattern (which is not good usually). It's possible to do better with some amount of voodoo though. I think that SimpleInjector has a lot of examples and tutorials on how to apply DI to filters in MVC, maybe they even have a nuget package now to ahieve that.
Will be thankful for your attention, time and efforts !
I have the following code
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Role { get; set; }
}
public interface IEmployeeRepository
{
Employee GetEmployee(string firstName, string role);
}
public class EmployeeRepository : IEmployeeRepository
{
public Employee GetEmployee(string firstName, string role)
{
//logic here
return new Employee();
}
}
Now i want to implement cache for EmployeeRepository.
At first i did it using Proxy design pattern
public class ProxyEmployeeRepository : IEmployeeRepository
{
private EmployeeRepository _employeeRepository = new EmployeeRepository();
private MemoryCache _cache = new MemoryCache("UsualCache");
public Employee GetEmployee(string firstName, string role)
{
//do not cache administrators
if (role == "admin")
{
return _employeeRepository.GetEmployee(firstName, role);
}
else
{
//get from cache at first
//if absent call _employeeRepository.GetEmployee and add to cache
//...
}
}
But when wanted to write unit tests for this class i couldn't do it(i cannot create mock for _employeeRepository and verify whether it was called or not)
If i implement cache with Decorator pattern then i would have the following code
public class DecoratorEmployeeRepository : IEmployeeRepository
{
private IEmployeeRepository _employeeRepository;
public DecoratorEmployeeRepository(IEmployeeRepository repository)
{
_employeeRepository = repository;
}
private MemoryCache _cache = new MemoryCache("UsualCache");
public Employee GetEmployee(string firstName, string role)
{
//do not cache administrators
if (role == "admin")
{
return _employeeRepository.GetEmployee(firstName, role);
}
else
{
//get from cache at first
//if absent call _employeeRepository.GetEmployee and add to cache
return null;
}
}
}
and unit tests for it
[TestClass]
public class EmployeeRepositoryTests
{
[TestMethod]
public void GetEmployeeTest_AdminRole()
{
var innerMock = Substitute.For<IEmployeeRepository>();
var employeeRepository = new DecoratorEmployeeRepository(innerMock);
employeeRepository.GetEmployee("Ihor", "admin");
innerMock.Received().GetEmployee(Arg.Any<string>(), Arg.Any<string>());
}
[TestMethod]
public void GetEmployeeTest_NotAdminRole()
{
var innerMock = Substitute.For<IEmployeeRepository>();
var employeeRepository = new DecoratorEmployeeRepository(innerMock);
employeeRepository.GetEmployee("Ihor", "NotAdmin");
innerMock.DidNotReceive().GetEmployee("Ihor", "NotAdmin");
}
}
Is it possible to write unit tests for first approach with proxy pattern ? i just don't understand how it is possible to cover proxy class with unit tests ...
I know it is too late to answer your question but it might help other new visitors:
I think your problem is your misunderstanding of both patterns. By using composition instead of instantiating your class inside the proxy, does not necessarily mean that you have changed your pattern from proxy to decorator. Each of these patterns is solving a specific problem. Let me clarify each:
Decorator Pattern:
This pattern is useful when you have different kinds of behaviours in your main class (like caching, logging, lazy loading and etc.) and you want to use each of these or a combination of them in different places of your application. For example, in your controller, you need only caching, in the admin controller you don't need caching but logging and in another service, you need both plus lazy loading. Therefore you will create three decorators for each extra behaviour (caching, logging and lazy loading) and in each place, you link the decorators into each other to provide various kinds of behaviours. The benefit of this pattern is that each class has only one responsibility. Additionally, your application is open to extension and close to modification. If you need a new behaviour, you can simply implement a new decorator from the interface and add it only to the services or controllers that the new behaviour is required without modifying the current implementation.
Proxy Pattern:
This pattern is useful when you want to add specific behaviour or behaviours that are required for your class but can prevent the actual behaviour (querying the database) and/or new behaviours come into the picture (which is not the behaviour in the decorator pattern. It only enhances the main behaviour). Another usage of this pattern is when instantiating the main class is costly. So in contrast, you do not need each behaviour (or various combination of them) separately in several places of your application.
The benefit of this pattern is that it prevents adding several responsibilities to your main class. Besides, it is still close to modification and open to extension. If the requirements change in future, you can simply implement a new proxy and replace it with the correct one or use it separately.
The answer to your question:
Therefore, as I mentioned above, by having a composition to your interface instead of instantiating it directly, you are not changing the pattern. In proxy pattern, the main class can be injected via the interface or the concrete implementation as well.
I have a scenario using WebApi, Generic Repository, EF6 and unit of work pattern
(in order to wrap all changes from several calls to the same context.)
Manager layer is used to perform calls to different repositories and also to other managers.
Currently Customer Manager does inject both repos and other Managers like:
public class CustomerManager {
public CustomerManager(IRepository<Customer> _customerRepository, IRepository<Order> orderRepository, IManager itemManager) {
_orderReporsitory = orderReporsitory;
_itemManager = itemManager;
_customerRepository = customerRepository;
}
public bool Save(Customer customer) {
_orderReporsitory.Find...
_itemManager.IsItemUnique(ItemId)
_customerRepository.Save(customer);
}
}
This code does not compile, for reference only.
Approaches like this
http://blog.longle.net/2013/05/11/genericizing-the-unit-of-work-pattern-repository-pattern-with-entity-framework-in-mvc/
Will wrap several repositories under a unit of work and flush the changes all together.
My issue involves also adding another Manager layer, to be wrapped also inside unit of work and allow both calls to repositories and other managers
(as I want to reuse some manager logic. Like in the example, I am re-using some ItemManager logic)
This code https://stackoverflow.com/a/15527444/310107
using (var uow = new UnitOfWork<CompanyContext>())
{
var catService = new Services.CategoryService(uow);
var custService = new Services.CustomerService(uow);
var cat = new Model.Category { Name = catName };
catService.Add(dep);
custService.Add(new Model.Customer { Name = custName, Category = cat });
uow.Save();
}
is using something similar of what I need but I would also like to be able to inject the services to unit test them (and not creating instances in the body of my manager/service method)
What would the best approach to do this ?
Thanks
Your code snippet with the unit of work has several problems, such as:
You create and dispose the unit of work explicitly within that method, forcing you to pass along that unit of work from method to method and class to class.
This causes you to violate the Dependency Inversion Principle, because you now depend on concrete types (CategoryService and CustomerService), which complicates your code and makes your code harder to test.
If you need to change the way the unit of work is created, managed or disposed, you will have to make sweeping changes throughout the application; A violation of the Open/Closed Principle.
I expressed these problems in more details in this answer.
Instead, I propose to have one DbContext, share it through a complete request, and control its lifetime in the application's infrastructure, instead of explicitly throughout the code base.
A very effective way of doing this is by placing your service layer behind a generic abstaction. Although the name of this abstraction is irrelevant, I usually call this abstraction 'command handler:
public interface ICommandHandler<TCommand>
{
void Handle(TCommand command);
}
There are a few interesting things about this abstaction:
The abstraction describes one service operation or use case.
Any arguments the operation might have are wrapped in a single message (the command).
Each operation gets its own unique command class.
Your CustomerManager for instance, might look as follows:
[Permission(Permissions.ManageCustomerDetails)]
public class UpdateCustomerDetailsCommand {
public Guid CustomerId { get; set; }
[Required] public string FirstName { get; set; }
[Required] public string LastName { get; set; }
[ValidBirthDate] public DateTime DateOfBirth { get; set; }
}
public class UpdateCustomerDetailsCommandHandler
: ICommandHandler<UpdateCustomerDetailsCommand> {
public UpdateCustomerDetailsCommandHandler(
IRepository<Customer> _customerRepository,
IRepository<Order> orderRepository,
IManager itemManager) {
_orderReporsitory = orderReporsitory;
_itemManager = itemManager;
_customerRepository = customerRepository;
}
public void Handle(UpdateCustomerDetailsCommand command) {
var customer = _customerRepository.GetById(command.CustomerId);
customer.FirstName = command.FirstName;
customer.LastName = command.LastName;
customer.DateOfBirth = command.DateOfBirth;
}
}
This might look like just a bunch of extra code, but having this message and this generic abstraction allows us to easily apply cross-cutting concerns, such as handling the unit of work for instance:
public class CommitUnitOfWorkCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand> {
private readonly IUnitOfWork unitOfWork;
private readonly ICommandHandler<TCommand> decoratee;
public CommitUnitOfWorkCommandHandlerDecorator(
IUnitOfWork unitOfWork,
ICommandHandler<TCommand> decoratee) {
this.unitOfWork = unitOfWork;
this.decoratee = decoratee;
}
public void Handle(TCommand command) {
this.decoratee.Handle(command);
this.unitOfWork.SaveChanges();
}
}
The class above is a decorator: It both implements ICommandHandler<TCommand> and it wraps ICommandHandler<TCommand>. This allows you to wrap an instance of this decorator around each command handler implementation and allow the system to transparently save the changes made in the unit of work, without any piece of code having to do this explicitly.
It is also possible to create a new unit of work here, but the easiest thing to start with is to let the unit of work live for the duration of the (web) request.
This decorator will however just be the beginning of what you can do with decorators. For instance, it will be trivial to:
Apply security checks
Do user input validation
Run the operation in a transaction
Apply a deadlock retry mechanism.
Prevent reposts by doing deduplication.
Register each operation in an audit trail.
Store commands for queuing or background processing.
More information can be found in the articles, here, here and here.
I am just about to start on a project, where I will be using MVC5. But as I want to use IoC and later reuse my user tables, and add custom stuff to it, I am finding it very hard to see how I can use the new Identity framework that came with MVC5.
I am more and more looking towards basic forms auth. What are your solutions?
My needs:
User repository/service must be injected
User repository must reside in the DAL
User repository must be able to support other technologies than EF
Authentication with OpenID and OAuth must be somewhat easy to implement
MUST BE SECURE
Should be reusable in other projects, eg. WPF
I have been looking for a long time for an answer, but everything I see is hardcoded in the controller.
How are you solving this? Are you writing most from scratch, or can you bind into something that will scale to other .NET platforms as WCF and WPF?
The below code is taken directly from the AccountController in the default ASP.NET MVC 5 Template.
The first thing it does is a Bastard Injection.
[Authorize]
public class AccountController : Controller
{
public AccountController()
: this(
new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(
new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
}
The accepted answer will go to the person, that shows me what they have done, that incorporates the above requirements
Since this is .NET, the standard approach to security is to authenticate at the application boundary, and convert the authentication information into an IPrincipal. MVC supports this out of the box.
If you need other information gained during authentication, you can gather that at in the Composition Root and use it to compose your services.
As an example, imagine that you need the authenticated user's email address in a lower layer. Any class that requires the user's email address can simply request it as a Concrete Dependency:
public class EmailThingy
{
private readonly string userEmail;
public EmailThingy(string userEmail)
{
if (userEmail == null)
throw new ArgumentNullException("userEmail");
this.userEmail = userEmail;
}
// other members go here...
}
In ASP.NET MVC, the Composition Root is IControllerFactory. IIRC, you can pull the authentication data from within the CreateController method and use it to compose your object graph.
These days, I use IPrincipal in the same way: I inject it as a dependency, instead of relying on the Thread.CurrentPrincipal Ambient Context, because it's easier to unit test when everything is consistently injected via Constructor Injection.
You might be interested to get a look at Thinktecture.IdentityServer.v2 https://github.com/thinktecture/Thinktecture.IdentityServer.v2. Many of your concerns are already implemented and encapsulated. If you don't find what you need you'll have to think about how to abstract all these concerns and implement it on your own.
I ended up deciding to implement the IUserStore, IUserStore, IUserPasswordStore, IUserLoginStore, to be able to move the UserRepository down into it's rightful place, the DataAccess Layer. But still get the Security Benifits of the Owin and new Identity Framework.
It's quite easy to implement, and doesn't take much to abstract it. Here is a taste of the UserStoreWrapper
namespace qubis.booking.WebApp.App_Code.Identity
{
public class UserServiceWrapper : IUserStore<ApplicationUserWrapper>,
IUserPasswordStore<ApplicationUserWrapper>,
IUserLoginStore<ApplicationUserWrapper>
{
public IUserRepository UserRepos { get; set; } // My own Interface.
public UserServiceWrapper(IUserRepository userRepo)
{
UserRepos = userRepo;
}
public async Task CreateAsync(ApplicationUserWrapper user)
{
UserRepos.Insert(user.RealUser);
}
public async Task<ApplicationUserWrapper> FindByIdAsync(string userId)
{
var appUser = UserRepos.FindByUserName(userId);
ApplicationUserWrapper wrappedUser;
if (appUser != null)
{
wrappedUser = new ApplicationUserWrapper(appUser);
}
else
wrappedUser = null;
return wrappedUser;
}
In the Account controller I Simply just ask for it to be injected:
public AccountController(UserManager<ApplicationUserWrapper> userManager)
{
UserManager = userManager;{ AllowOnlyAlphanumericUserNames = false };
}
And as I am using Ninject I just set it upin the kernel like so:
// <summary>
// Load your modules or register your services here!
// </summary>
// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserStore<ApplicationUserWrapper>>().To<UserServiceWrapper>();
kernel.Bind<UserManager<ApplicationUserWrapper>>().ToSelf();
}
To see the Identity frameworks structure, please see this article. http://www.asp.net/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider
If all you need is to inject custom UserStore implementation this article may help you
Basically you need to inject this (depends if you want to use roles, claims etc..):
Write a User class that implements the IUser interface
public class IdentityUser : IUser {
public IdentityUser(){...}
public IdentityUser(string userName) (){...}
public string Id { get; set; }
public string UserName { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
}
Write a User store class that implements the IUserStore, IUserClaimStore, IUserLoginStore, IUserRoleStore and IUserPasswordStore
public class UserStore : IUserStore<IdentityUser>,
IUserClaimStore<IdentityUser>,
IUserLoginStore<IdentityUser>,
IUserRoleStore<IdentityUser>,
IUserPasswordStore<IdentityUser> {
public UserStore(){...}
public Task CreateAsync(IdentityUser user){...}
public Task<IdentityUser> FindByIdAsync(string userId){...}
.. .
}