ASP.NET MVC Configuration Class using IoC - asp.net-mvc

In an MVC app, we the have need to create a configuration settings class that is needed throughout the app. It is a cross-cutting concern in that it is need in controllers, sometimes deep in the domain logic, as well as place like HtmlHelper extensions. The fact that it's needed is so many different places is what is tripping me up.
The class will wrap settings that are pulled from the web.config, as well as a table in a DB. The DB settings query will be cached so I'm not worried about that getting hit up for every request.
In years past I may have created some static type of class or singleton, but I don't want to lose the testability I have now. What would be the best way to instantiate this class and then to be able to access it through pretty much anywhere in the app?

I would continue to use a singleton. But a singleton which is wrapping an interface, which also makes it testable.
public class Configuration
{
private IConfiguration _config;
public static IConfiguration Instance { get { return _config; }}
public static void Assign(IConfiguration config)
{
_config = config;
}
}
Simply use Assign in global.asax or any of your unit tests.
If you want to do it the correct way, you should provide the configuration settings directly in the constructors of your objects.
Instead of
public class MyService
{
public MyService()
{
var confString = Configuration.Instance.GetConnectionString()
}
}
You would do:
public class MyService
{
public MyService(string confString)
{}
}
Finally, I would not have any configuration dependencies in HTML helpers. By doing so yuo are adding business logic to your views which breaks separation of concerns

I think the codeplex project mvccontrib provided some hooks to use
at least 3 IOC providers as far as I not windsor, structurmap, spring.net...
but I did not used it myself
you can find out more here
http://mvccontrib.codeplex.com/
and maybe you can look into the sourcecode of this project and see where you can go from there...
HTH

I would refactor my app not to use configuration everywhere. I use configuration in controllers only. My views do not have any logic, my domain model does just have business logic, not application logic.

Related

Why pass a parameters of multiple services to mvc controller?

I'm new to asp.net mvc world mostly a windows developer moving to web. Be nice...
I found ridiculous when I look at many examples of asp.net mvc web applications that the pass to their controllers a list of services
Like this
public CustomerController(ICustomerService customerService,
IAnotherService anotherService,
IYetAnotherService yetAnotherService,
IYetAgainAnotherService yetAgainAnotherService,
etc...
Would not be better to do something like
public CustomerController(IServices services)
{
}
public interface IServices
{
ICustomerService CustomerService{get;set;}
IAnotherServiceService AnotherService{get;set;}
IYetAnotherServiceService YetAnotherServiceService{get;set;}
}
Am I missing the obvious?
As anybody implemented the way I suggest in mvc4 or mvc5. I know mvc6 does it.
But I cannot use mvc6 at work.
Any samples using DI?
Thanks
What you're missing here is the fact that constructors with many parameters is a code smell often caused by that class having to many responsibilities: it violates the Single Responsibility Principle.
So instead of packaging the services to inject into a 'container' class that allows those services to be accessible using a public property, consider the following refactorings:
Divide the class into multiple smaller classes.
Extract logic that implements cross-cutting concerns (such as logging, audit trailing, validation, etc, etc)out of the class and apply those cross-cutting concerns using decorators, global filters (MVC) or message handlers (Web API). A great pattern for your business logic is the command/handler pattern.
Extract logic that uses multiple dependencies out of the class and hide that logic behind a new abstraction that does not expose the wrapped dependencies. This newly created abstraction is called an Aggregate Service.
I agree that for readability sake, even if you have multiple existing services which are also used in other applications, you could always wrap them in another class to avoid passing a long list of dependencies to the controllers.
When you have code in the API controllers that look like this:
public CustomerController(ICustomerService customerService,
IAnotherService anotherService,
IYetAnotherService yetAnotherService,
IYetAgainAnotherService yetAgainAnotherService,
...
That can be a code-smell and is an opportunity to refactor. But this does not mean the original code was a bad design. What I mean is in the API layer, we try not to clutter it with too many services that the controller is dependent on. Instead you can create a facade service. So in your example above, you refactor it to look like this:
public CustomerController(IServices services)
{
}
public interface IServices
{
ICustomerService CustomerService{get;set;}
IAnotherServiceService AnotherService{get;set;}
IYetAnotherServiceService YetAnotherServiceService{get;set;}
}
Which is good and then you can move the IServices to your service/business layer. The concrete implementation of that in the service/business layer will look like this:
public class AConcreteService:IServices {
public AConcreteService(ICustomerService cs, IAnotherServiceService as, IYetAnotherServiceService yas)
{
...
}
public List<Customer> GetCustomers(){
return _cs.GetCustomers();
}
public List<string> GetAnotherServiceData(){
return _as.AnotherServiceData();
}
public List<string> GetYetAnotherServiceData(){
return _yas.YetAnotherServiceData();
}
...
So that code will end up looking like your original code when implemented directly in the controller but is now in the service/business layer. This time it will be easy to unit test in the service class and the API layer will look much cleaner.

where to keep frequently used methods in MVC

I need to implement MVC architecture in my company, So can anyone suggest where to keep frequently used methods to call on all pages. Like:
states ddl, departments ddl also roles list and etc...
Please give me suggestions where to keep them in architecture.
Thanks
There are different solutions depending on the scale of your application. For small projects, you can simply create a set of classes in MVC application itself. Just create a Utils folder and a DropDownLists class and away you go. For simple stuff like this, I find it's acceptable to have static methods that return the data, lists, or enumerations you require.
Another option is to create an abstract MyControllerBase class that descends from Controller and put your cross-cutting concerns in there, perhaps as virtual methods or properties. Then all your actual controllers can descend from MyControllerBase.
For larger applications, or in situations where you might share these classes with other MVC applications, create a shared library such as MySolution.Utils and reference the library from all projects as required.
Yet another possibility for larger solutions is to use Dependency Injection to inject the requirements in at runtime. You might consider using something like Unity or Ninject for this task.
Example, as per your request (also in GitHub Gist)
// declare these in a shared library
public interface ILookupDataProvider
{
IEnumerable<string> States { get; }
}
public class LookupDataProvider: ILookupDataProvider
{
public IEnumerable<string> States
{
get
{
return new string[] { "A", "B", "C" };
}
}
}
// then inject the requirement in to your controller
// in this example, the [Dependency] attribute comes from Unity (other DI containers are available!)
public class MyController : Controller
{
[Dependency]
public ILookupDataProvider LookupDataProvider { get; set; }
public ActionResult Index()
{
var myModel = new MyModel
{
States = LookupDataProvider.States
};
return View(myModel);
}
}
In the code above, you'll need to configure your Dependency Injection technology but this is definitely outside the scope of the answer (check SO for help here). Once configured correctly, the concrete implementation of ILookupDataProvider will be injected in at runtime to provide the data.
One final solution I would suggest, albeit this would be very much overkill for small projects would be to host shared services in a WCF service layer. This allows parts of your application to be separated out in to highly-scalable services, should the need arise in the future.

Dependancy issue with static utility classes with repository (.NET MVC project)

I have an MVC project with the standard IoC setup that uses StructureMap to inject repositories into controller constructors.
I also decided I wanted to have a static "utilities" class where I could have common methods that can be called by different controllers. So for example, I have:
public static IEnumerable<CountryCode> GetCountryList()
{
ICountryCodeRepository repo = ObjectFactory.GetInstance<ICountryCodeRepository>();
IEnumerable<CountryCode> countries = repo.GetAll();
return countries;
}
As you can see, that directly creates a repo object from the ObjectFactory. The problem, now, is that when I want to unit-test my controllers, I can mock the repos for the controllers, but not the repos in the utilities class (which the controller eventually calls) I'm sure there are other reasons why my utilities class is wrong, but this is what I see so far. I've also read some stuff saying what I have is bad design, I just don't know how to fix it.
I was thinking about having the GetCountryList() function to accept a repo object
GetCountryList(ICountryCodeRepository _repo)
and the calling controller would pass it in, but isn't that just creating another dependency concern because all controllers will have to know what the utility functions need?
Or is it possible to use StructureMap somehow to inject these utility methods?
It's at least OK that you know that what you are doing is bad design. That's fine and people reading this post will know it as well and avoid doing the same mistake as you.
But now to the point, you could use a provider in your static class:
public static class Foo
{
public static Func<ICountryCodeRepository> CountryRepoProvider =
() => ObjectFactory.GetInstance<ICountryCodeRepository>();
public static IEnumerable<CountryCode> GetCountryList()
{
return CountryRepoProvider().GetAll();
}
}
and now in your unit test you could mock it:
Foo.CountryRepoProvider = () => mocha;
or if you are using ASP.NET MVC 3 and you DI framework uses a dependency resolver you could improve this code by at least making it DI framework agnostic:
public static IEnumerable<CountryCode> GetCountryList()
{
var repo = DependencyResolver.Current.GetService<ICountryCodeRepository>();
return repo.GetAll();
}
Now in your unit test you could of course write a custom dependency resolver which will spit mocked instances of your services.
And now when you look at this code you might really say to yourself: What am I doing? I am writing a static class with one liner methods delegating to a repository I am fetching from the DI. What's the point when I can benefit from my DI framework to directly inject the instance of this repository wherever I need it and then simply call the method I need on it? What am I unit testing in those one liner static methods? Why am I wasting my time.
And if of course you had more complex logic to handle you would simply write a service layer which will take the necessary repositories as constructor dependencies and perform the complex business operations on them. Then you will simply configure your DI framework to inject those ready to be used instance of the service in your controllers or wherever you need it. See? No need of any static class. Weak coupling and unit testing friendly code.

Ninject.Extensions.Logging.nlog2 - How to?

Browsing the nuget library, i came across Ninject.Extensions.Logging.nlog2. Some googling and trying to figure things out, I can't seem to find how or why you would use this extension.
Is it advisable to use with MVC 3?
What exactly is the point?
How do you use it?
It's really very simple; both NLog and log4net expect you to use singleton/static references to obtain logger instances:
private static Logger logger = LogManager.GetCurrentClassLogger();
This is widely considered to be an anti-pattern, but even if you have no problem with it, it's still going against the grain if you're trying to implement dependency injection. In the case of NLog it's not even an ILog or ILogger interface like log4net, it's an actual class. That carries certain disadvantages such as the inability to create proxies, deferred loading, caching, etc.
What the Ninject.Extensions.Logging project does is first provide an abstract ILogger class with simple methods like Info, Error, etc., so you can inject it as a dependency and switch the logging framework if you want:
public class WidgetProvider
{
private readonly ILogger log;
public WidgetProvider(ILogger log)
{
this.log = log;
}
}
This is how DI is supposed to work - a class never goes out to grab its own dependencies, instead they're supplied by the constructor or caller as above. Assuming you've already integrated Ninject itself into your project, that's really all you have to do, there is no additional work.
As for what Ninject.Extensions.Logging.NLog2 does specifically - it just provides an implementation for Ninject.Extensions.Logging based on NLog2. The base Logging library doesn't actually contain any implementations of ILogger, you have to plug in one of the specific libraries (NLog, NLog2, or log4net) in order to get it to work.
If you switch your DI library more often than you switch loggers then don't bother with it. But if you're like me and use Ninject in almost every project, then it's a nice way to decouple your code from any specific logging library.
If you want to use dependency injection via the constructor you can pass the ILoggerFactory interface.
This is how I did it.
using Ninject.Extensions.Logging;
public class MyClass
{
private readonly ILogger _log;
public MyClass(ILoggerFactory logFactory)
{
_log = logFactory.GetCurrentClassLogger();
}
public void DoWork()
{
_log.Info("Doing work!");
}
}
Problem solved!
Hope this helps someone.

DDD and constructor explosion

I'm practicing DDD with ASP.NET MVC and come to a situation where my controllers have many dependencies on different services and repositories, and testing becomes very tedious.
In general, I have a service or repository for each aggregate root. Consider a page which will list a customer, along with it's orders and a dropdown of different packages and sellers. All of those types are aggregate roots. For this to work, I need a CustomerService, OrderService, PackageRepository and a UserRepository. Like this:
public class OrderController {
public OrderController(Customerservice customerService,
OrderService orderService, Repository<Package> packageRepository,
Repository<User> userRepository)
{
_customerService = customerService
..
}
}
Imagine the number of dependencies and constructor parameters required to render a more complex view.
Maybe I'm approaching my service layer wrong; I could have a CustomerService which takes care of all this, but my service constructor will then explode. I think I'm violating SRP too much.
I think I'm violating SRP too much.
Bingo.
I find that using a command processing layer makes my applications architecture cleaner and more consistent.
Basically, each service method becomes a command handler class (and the method parameters become a command class), and every query is also its own class.
This won't actually reduce your dependencies - your query will likely still require those same couple of services and repositories to provide the correct data; however, when using an IoC framework like Ninject or Spring it won't matter because they will inject what is needed up the whole chain - and testing should be much easier as a dependency on a specific query is easier to fill and test than a dependency on a service class with many marginally related methods.
Also, now the relationship between the Controller and its dependencies is clear, logic has been removed from the Controller, and the query and command classes are more focused on their individual responsibilities.
Yes, this does cause a bit of an explosion of classes and files. Employing proper Object Oriented Programming will tend to do that. But, frankly, what's easier to find/organize/manage - a function in a file of dozens of other semi-related functions or a single file in a directory of dozens of semi-related files. I think that latter hands down.
Code Better had a blog post recently that nearly matches my preferred way of organizing controllers and commands in an MVC app.
Well you can solve this issue easily by using the RenderAction. Just create separate controllers or introduce child actions in those controllers. Now in the main view call render actions with the required parameters. This will give you a nice composite view.
Why not have a service for this scenario to return a view model for you? That way you only have one dependency in the controller although your service may have the separate dependencies
the book dependency injection in .net suggests introducing "facade services" where you'd group related services together then inject the facade instead if you feel like you have too many constructor parameters.
Update: I finally had some available time, so I ended up finally creating an implementation for what I was talking about in my post below. My implementation is:
public class WindsorServiceFactory : IServiceFactory
{
protected IWindsorContainer _container;
public WindsorServiceFactory(IWindsorContainer windsorContainer)
{
_container = windsorContainer;
}
public ServiceType GetService<ServiceType>() where ServiceType : class
{
// Use windsor to resolve the service class. If the dependency can't be resolved throw an exception
try { return _container.Resolve<ServiceType>(); }
catch (ComponentNotFoundException) { throw new ServiceNotFoundException(typeof(ServiceType)); }
}
}
All that is needed now is to pass my IServiceFactory into my controller constructors, and I am now able to keep my constructors clean while still allowing easy (and flexible) unit tests. More details can be found at my blog blog if you are interested.
I have noticed the same issue creeping up in my MVC app, and your question got me thinking of how I want to handle this. As I'm using a command and query approach (where each action or query is a separate service class) my controllers are already getting out of hand, and will probably be even worse later on.
After thinking about this I think the route I am going to look at going is to create a SerivceFactory class, which would look like:
public class ServiceFactory
{
public ServiceFactory( UserService userService, CustomerService customerService, etc...)
{
// Code to set private service references here
}
public T GetService<T>(Type serviceType) where T : IService
{
// Determine if serviceType is a valid service type,
// and return the instantiated version of that service class
// otherwise throw error
}
}
Note that I wrote this up in Notepad++ off hand so I am pretty sure I got the generics part of the GetService method syntactically wrong , but that's the general idea. So then your controller will end up looking like this:
public class OrderController {
public OrderController(ServiceFactory factory) {
_factory = factory;
}
}
You would then have IoC instantiate your ServiceFactory instance, and everything should work as expected.
The good part about this is that if you realize that you have to use the ProductService class in your controller, you don't have to mess with controller's constructor at all, you only have to just call _factory.GetService() for your intended service in the action method.
Finally, this approach allows you to still mock services out (one of the big reasons for using IoC and passing them straight into the controller's constructor) by just creating a new ServiceFactory in your test code with the mocked services passed in (the rest left as null).
I think this will keep a good balance out the best world of flexibility and testability, and keeps service instantiation in one spot.
After typing this all out I'm actually excited to go home and implement this in my app :)

Resources