I am developing a simple project in MVC 6 and bit confused about whether to use DI or not.
I have a view that POSTs to an action - AddData(). Now inside AddData() action I instantiate a couple of classes, say Class1 and Class2, and then invoke their methods to get the job done.
Now my confusion is - In MVC 5 I used to create local instances of Class1 and Class2 inside the action and then call methods on them. This was without any DI.
In MVC 6 do I need to DI Class1 and Class2 in the controller? They are needed only in AddData() action. So is this situation good for DI or traditional local objects would be better?
Please clarify.
Dependency injection is a tool on your developer toolbox that should be used when needed. It will allow you to follow principles like SOLID, which will make your application design better, and it will be of invaluable help if you plan to do unit testing.
IMHO it is a great thing that dependency injection is now fully
integrated across the whole ASP 5 pipeline. This way, whenever you
need it, you won't have to fight the framework as the seam for your
code is already there.
But the fact that you can now use it, doesn't mean you should always use it. Use your judgement!
If you are writing some throwaway code or a very simple app, and you really think dependency injection is overkill, then don't use it. But at least you have taken a conscious decision!
Of course, the easier it is to apply DI, the more you might end up using it even for simple projects or throwaway code.
It is better to do so, so that in case you want to test your app later on, you can substitute with mocks, for instance. However, if you do not care about testing or if the app is really simple, then I don't see a reason against simply instantiating them inside the controller.
Without knowing what "Class1" and "Class2" are used for, this can't really be answered.
If they are models, then no, you wouldn't use DI.
If they are services/utilities, then yes, ideally use DI.
However - there's no difference in the architecture of DI between MVC5 and MVC6, so if you are not using DI in MVC5 then there's no reason to suddenly need to when you move to MVC6 unless you want to improve your practices.
Note there are some 'simple' IoC/DI frameworks that make this very easy and you can always use "poor man's DI" where you have a constructor with the class and one without, eg:
public Controller1()
{
this.class1 = new Class1();
}
public Controller1(Class1 class1)
{
this.class1 = class1;
}
(many people discourage this, but it's an option)
Related
i am using EF4 and StructureMap in an asp.net web application. I am using the repository/unit of work patterns as detailed in this post. In the code, there is a line that delegates the setup of an ObjectContext in global.asax.
EntityUnitOfWorkFactory.SetObjectContext(() => new MyObjectContext());
On the web page code-behind, you can create a generic repository interface like so ...
IRepository<MyPocoObject> ds = ObjectFactory.GetInstance<IRepository<MyPocoObject>>();
My question is what is a good approach to refactoring this code so that I can use more than one ObjectContext and differentiate between them in the code-behind? Basically i have two databases/entity models in my application and need to query them both on the same page.
The Unit of Work is used to manage persistence across multiple repositories, not multiple object contexts.
You're not going to be able to persist changes across multiple contexts using a unit of work, as the UoW is simply implemented as a wrapper for a ObjectContext. Therefore, you'll need two unit of works.
Overall, things are going to get messy. You're going to have two OCs newed up and disposed each HTTP request, not to mention transaction management is going to be a nightmare.
Must you have two ObjectContexts? What is the reasoning for this? If it's for scalability, don't bother; it's going to be too painful for other things like your repository, unit of work and http scope management.
It's hard to provide good advice without seeing how you have your repositories set up.
Try creating wrapper classes for each object context, each implementing IUnitOfWork and a secondary unique interface (IEfSqlContext1, etc which represents one of your models/contexts).
Then you can inject whichever context you want.
As I said though, try and avoid having two EDMX/Contexts. It's more trouble than it's worth.
I am developing using TDD and ASP.Net MVC.
I have a custom ActionFilterAttribute which needs to be applied to certain controller actions and was wondering the best approach to this using TDD.
Currently the attribute itself has a
set of unit tests.
I develop the
controller action with tests as per
normal but ignore the case handled by
the attribute.
I add a unit test that
uses relfection to ensure the
attribute is applied (with correct
parameters) to the action.
If this a suitable way to go about it?
It sounds like it is.
What confuses You? Test that tests if attribute is applied? There is nothing bad with that. Testing actual constructions of code is very useful technique. You can force various conventions too with this approach like naming of classes in particular namespace, existence of public constructors w/o arguments, etc.
I have been working in an MVC project, and have seen both of these used. I was wondering what the difference between them is? Is it incorrect to use one over the other? My understanding is that I should be using Url.Content(), but VirtualPathUtility.ToAbsolute() seems to be working as well.
Url.Content() is an utility method part of MVC. Being there to uniformize and centralize utility classes I guess.
VirtualPathUtility.ToAbsolute() is a .NET Framework method. Maybe the MVC one is using it, we would have to check the source...
Hope the helps
If you are doing this conversion within a Controller, then I'd favour VirtualParthUtility.ToAbsolute() over Url.Content().
The benefit comes when you want to unit test the controller actions. Rather than call it directly though, I'd define an interface IPathUtilities, say, with one implementation using VirtualPathUtility methods for the live site, and another using some sort of mock when testing.
If you call VirtualPathUtility directly, then you won't be able to test the action method (you might have thought some clever mocking of HttpContext would get round this, but having tried this myself I couldn't find a way to do it).
I keep hearing about the DRY Principle and how it is so important in ASP.NET MVC, but when I do research on Google I don't seem to quite understand exactly how it applies to MVC.
From what I've read its not really the copy & paste code smell, which I thought it was, but it is more than that.
Can any of you give some insight into how I might use the DRY Principle in my ASP.NET MVC application?
DRY just means "Don't Repeat Yourself". Make sure that when you write code, you only write it one time. If you find yourself writing similar functionality in all of your Controller classes, make a base controller class that has the functionality and then inherit from it, or move the functionality into another class and call it from there instead of repeating it in all the controllers.
use filter attributes to manage aspects (authentication, navigation, breadcrumbs, etc)
use a layer supertype controller (apply common controller-level filters to it, see mvccontrib for an example)
write custom actionresults (like in mvccontrib - for example we made one called logoutresult that just does a FormsAuthentication.Logout()
use a convention for view names
most importantly - keep you controller actions dumb, look for reuse opportunities in services
Don't Repeat Yourself. It can apply to many different aspects of programming. The most basic level of this is prevent code smell. I haven't used ASP.NET so I can't get specific to it and MVC's.
In C++ Templating prevets multiple copies of the same function.
In C void * pointers can be used in a similar fashion, but with great care.
Inheriting from another function allows function allows other functions to use the same code base without having to copy the code.
Normalizing data in a database minimizes redundant data. Also adhereing to the DRY principle.
When you go over a "thought" in a project. Ask yourself.
Have I already wrote this code?
Will this code be useful elsewhere.
Can I save coding by building off of a previous class/function.
DRY is not specific to any one technology. Just make sure you look at your classes from a functionality standpoint (not even from a copy/paste coder view) and see where the duplication occurs. This process will probably not happen in one sitting, and you will only notice duplication after reviewing your code several months later when adding a new feature. If you have unit tests, you should have no fear in removing that duplication.
One advantage of MVC as related to not repeating yourself is that your controller can do tasks common to all pages in the one class. For example, validating against certain types of malicious requests or validating authentication can be centralized.
DRY should not only be applied to code, but to information in general. Are you repeating things in your build system? Do you have data which should be moved to a common configuration file, etc.
Well, the most common example that I can give about DRY and UI is using things like MasterPages and UserControls.
MasterPages ensure that you have written all the static HTML only once.
UserControls ensure reusability of code. Example, you will have a lot of forms doing basic stuff like CRUD. Now, ideally we want all users to see different pages for Create and Update though the forms fields in both will almost be the same. What we can do is combine all the common controls and put them into a control that can be reused over both the pages. This ensures that we are never retyping (or copy-pasting) the same code.
DRY is especially important in MVC because of the increase in the sheer number of files to accomplish the same task.
There seems to be a misconception that everything in a domain model has to be copied up as a special view model. You can have domain models be domain models but view models be something that know nothing of domain specifics and be more generic. For example:
Domain Model classes: Account, Asset, PurchaseOrder
View Model: List, Table, Tuple, SearchFormBackingModel:Checked options, Outputoptions, etc. The view itself might be much more view implementation specific.
The Tuple/Dictonary/Map might map to Account, Asset and PurchaseOrder single instances but a Table might be useful for a collection of them etc. You still have MVC but you have session data, not ready for transaction yet in a view model without necessarily having it violate the rules of your domain model which is where the rules should go. They will be less anemic and anti-pattern that way. You can pass these rules up front and use them there or just in back or both depending on how the system reads from clients etc.
Alright.
So I figure it's about time I get into unit testing, since everyone's been banging on about it for long enough. I've installed NUnit and gone through a few "intro to unit testing" type tutorials.
I'm currently putting together a small framework to help with the rebuild of one of our web apps, so I've created a VS2008 project for my framework and I want to unit test it as I go.
How on earth do I go about unit testing the WebControls? The methods are all protected or private, and since it's a framework, there isn't much else but WebControls.
Any pointers?
Burns
You can do model-view-controller or model-view-presenter type architectures without using a full blown framework. You already found out that unit-testing ui-components is difficult. There are ways around that but you probably don't want to go that route. Usually this will make your tests very hard to maintain, more maintenance nightmare's is something programmers can do without :-)
Try to separate out the functionality you want to test in a "controller" or "presenter" class. Then test that class. To make it more testable you can hide the usercontrol class (the view) behind an interface and make the controller or presenter talk to the view through the interface. That way you can mock up the view in your tests.
I know this sounds like a lot of work and it seems like a workaround but if you get used to this it's a realy nice architecture that makes it far easier to change ui behaviour. You can always start using a "real" mvc framework when you realy need it :-)
Ues the assembly:InternalsVisibleTo attribute and you'll be able to access those private members.
Put it in your webcontrol project's AssemblyInfo.cs (under Properties node)
[assembly:InternalsVisibleTo("YourTestProjectName")]
You have found the biggest pain point of ASP.NET. As far as sealed, private classes that hinder unit testing.
This is the main reason that TDD people will use a MVC framework (ASP.NET MVC, Castle MonoRail) as it provides a clear seperation from your view templates and your controller logic. The controllers are fully testable.
You could also look at testing components through the browser as a user would see them using a testing framework such as WebAii. I've seen it work and its pretty cool. I've also been told you can plug it into automated builds but I've not seen that as of yet.
Hope it helps ...
This is an old article by now, but I was using NUnitASP to write nunit tests for asp.net WebControls in 2004. That article gives a detailed example of testing a simple control using their concept of creating a corresponding "Tester" class that encapsulates the details of your control from you tests. The Tester can (should) also be in the same assembly as your control so can share some things between them (e.g. utility functions, constants, etc.).
I used the technique (and others use variants of the technique) still today to test very sophisticated controls.
I hope that is helpful.
The MVC framework mentioned above is the best way to test what the control does. However testing how it works is a bit different.
This is totally off the cuff but you could make the user control expose some protected methods and properties to return validation information and then have a testing user control inherit it. That control could populate fields, press buttons and what not. Kind of messy but it could work.
You can also take a look at this Rhino Igloo framework. It is a compromised MVC framework for WebForms.
Ivonna
can test WebControls in isolation, within the Asp.Net context
Just call session.GetControl("Path.ascx") and verify that it has all necessary properties.
You test them like this:
[Test]
public void ConditionQueryBuilderTest_RendersProperHtml()
{
var sw = new StringWriter();
var queryBuilder = new ConditionQueryBuilderStub
{
ID = "UnitTestbuilder",
QueryBuilderURL = #"\SomeAspxPage\SomeWebMethod",
ResetQueryBuilderURL = #"\SomeAspxPage\OnQueryBuilderReset",
FilterValuesCollection = new Dictionary<int, string> { {15, "Some Condition"}}
};
queryBuilder.RenderAllContents(new HtmlTextWriter(sw));
AppendLog(sw.ToString());
Assert.AreEqual(ExpectedHtml, sw.ToString()); // ExpectedHTML is the raw expected HTML
}
Here is my stub:
internal class ConditionQueryBuilderStub : ConditionQueryBuilder // ConditionQueryBuilder is a WebControl
{
internal void RenderAllContents(HtmlTextWriter writer)
{
RenderContents(writer);
}
}