Dependency injection in Umbraco or unit testing - asp.net-mvc

I have made a project in Umbraco using backoffice completely.But Now I am trying to apply concept of dependency injection(which I may have used in past..but not by that specific name) in that project.
and after loads of searching.I now know the concept of dependency injection(I think),in which we are supposed to use classes and constructor to restrict the input supplied to a function in terms of type,value.
But how am I suppose to make that umbraco project from that.I once tried making a strongly typed.It looks much like that which I am supposed to do now.
I also took reference from these articles.
Is it possible to use dependency injection with Umbraco 7 ContentService event handlers?
Why does one use dependency injection?
But still I am kind of stuck..Is there any other way to do unit testing in umbraco.

Yes, you can! :)
Basically, the starting URL for using IoC and DI with Umbraco was already shared. It's here: https://our.umbraco.org/documentation/reference/using-ioc. You can of course use any of the avaialable containers, the example is just for autofac. You just need to remember to initialize container when Umbraco starts (using event handlers).
For Unit Testing resources I would point you first to tests made by Umbraco itself: https://github.com/umbraco/Umbraco-CMS/tree/dev-v7/src/Umbraco.Tests. You can explore how the core team is testing their code and even reference this library and make use of it in your solution.
There are some other useful materials to start unit testing with Umbraco. To list a few:
http://blog.aabech.no/archive/the-basics-of-unit-testing-umbraco/
http://skrift.io/articles/archive/unit-testing-umbraco-plausible/
http://skrift.io/articles/archive/unit-testing-umbraco-with-umbraco-context-mock/
https://www.youtube.com/watch?v=1xS002NyGnc
I think it will be enough to start doing it.

Related

How do I convert a specific controller to a package to include in other projects?

VS2013, MVC5, VB
I am nearing the completion of a small project to manage the roles tables in a standard MVC5 application. The code is pretty much encapsulated. What are my options for using this 'package' in other projects?
Can I compile it into something? I know this type of action is possible, I'm just not familiar with the options available to me or the steps to do this. Links to sites that have tutorials are fine. Is creating a Nu Get package the only way to go, or is that even in the ballpark of what I'm asking. I say Nu Get, but I don't mean for public consumption, only for my consumption.
Will the finished 'whatever' include it's controller class, view models and views? Will I be able to easily manage updates? etc.
Creating a Nuget package is one way. I have created a local repository of common utilities for this purpose. But I usually use it just for DLLs. I use Nuget Package Explorer for its ease of use since its just me using the packages most of the time. Not sure its possible to place the files in specific directories.
Files in the content folder are copied to the root of your application when the package is installed. - Nuget
The alternative is to create an item template. I used to use this method for class files I want in my code but I can't see why you couldn't do it for the rest. Works well and isn't too hard to set up. There are dozens if not 100s of tutorials on the subject. Here is one on code project.

How to work with NopCommerce MVC as a team

We are currently looking at the newest version (2.60) of NopCommerce in MVC and we will be integrating it pretty soon…We’ve downloaded the Source Code and paid the 20$ for the User Guide documentation. The documentation is great! I mean…it is great in the sense that it explains how to deploy, install and how to work around the UI Frontend and Backend. This is great for an overall overview but what it lacks is the understanding of how to work with NopCommerce as a team. What are/is the best practices etc...
As an example (or parallel), if you decide to work with Dotnetnuke as a team, you usually work in the following fashion:
Each developer downloads/installs Dotnetnuke locally on their
machine.
You also download/install Dotnetnuke on a dedicated server (let’s say
dev-server).
As a developer, you work and create modules which you test locally
within your Dotnetnuke installation.
Once it is done, you package your module (and any SQL scripts that
comes with your module) into a zip file.
Once the package is ready, you upload/install that package on the
dedicated server (dev-server).
This approach works great for Dotnetnuke and more importantly if you have a team of developers creating modules.
My question is how does a team work with NopCommerce MVC?
I’m assuming it is a bad idea to directly work within the source code in case your team decides to modify core elements/source which will make any upgrade to newer versions impossible (or break changes).
I’m not sure if my parallel to Dotnetnuke is a correct one…but would anyone have any idea (or help me clarify) how does a team work with NopCommerce MVC.
In addition, should the team only rely on creating plugins for NopCommerce and stay away from modifying the core or should this be irrelevant?
What about adding new objects in SQL (or modifying existing ones) should we prefix our objects in case an eventual NopCommerce MVC upgrade creates similar objects and/or overwrites them?
Thank you for helping me shed some light on this.
Sincerely
Vince
Plugins in NopCommerce are almost like modules in DNN. Depending on what you need to do, it sometimes is necessary to modify the core code.
What I've been doing for the Services is create a new class and inherit from the existing service, then override the function you want to change. Create a new DependencyRegistrar class and set your new service classes as the implementation for that particular interface. Also make sure the Order property is 1 so that your DR class is loaded after the stock one. Since you're inheriting from the core class, any functions you didn't override will be handled by the parent class. If I need to add a new function, I'm just modifying the interface, putting a stub in the stock class, and implementing it in my own.
Views in the Nop.Web project can be overridden by Themes. The Admin stuff and the Web Controllers get trickier. I'm just modifying those files directly.
The Core and Data classes can be done using partial classes to add your new fields.
In any case you will still need to merge changes with your solution when an update is released. My opinion is that you are better off writing clean, readable code now and bite the merge bullet when it comes.
I don't really worry about SQL scripts right now because I'm a single developer but maybe you add a folder for ALTER scripts and name them after the day they were created. Then each dev knows which scripts they need to run when they get latest.

StructureMap configuration: Options to minimize dependencies on the StructureMap assembly

I understand how to implement a StructureMap registry, my question concerns the fact that every project that contains a StructureMap registry requires a static reference to the StructureMap assembly. Is there a best practice for how to structure the configuration for a large number of projects (30+) without forcing each project to take this dependency?
The alternative, I suppose, would be to create a bootstrapper assembly that could be referenced by the host process. The bootstrapper would perform all wire-up. In this scenario, the bootstrap assembly, instead, would have references to all of the projects. This has the upside of centralizing the reference to StructureMap so that all of the projects are unaware of StructureMap.
Using XML-based configuration is not an option for me.
Are there any other options for configuration that minimize the number of static references the projects in the solution must take? I'm guessing that there isn't, but thought I'd solicit some other opinions.
Technically, you only need a single project to reference the container framework, and that is the top-level application project. It references all the other projects and specifies the configuration of the components.
This puts the entire graph configuration out of the hands of each project, opting instead to define graphs only where they are used. This gives each application the complete freedom to configure components, rather than assuming the components will be used in the same way every time (as is implied by the registries which are inherent to each project).
An aside that may or may not be useful: in quantum physics, when we observe a particle, we collapse it from every possible state into a particular one. Frameworks are similar, in that they don't exist in a single state until they are observed, which here means "put to use in an application." This frames the application as the observer, which is the context in which the framework collapses into a single form.
Now, I generally wouldn't want the application be responsible for both being a running application and also configuring that runtime. For this reason, I tend to have a Composition project which references the others as well as the container framework. The actual application project can then reference the Composition project. This externalizes the registries from each project, including the application project, producing a cohesive assembly whose sole purpose is to define the composition of a particular application.

Determining missing dependencies statically when using dependency injection container

When using a dependency injection container, missing dependencies are detected when you execute resolve. This is at runtime.
This article describes a partial solution. It would help simplify test, debug, and maintenance, but it still requires tests to be executed to validate your behavior (especially if you use the abstract factory sub-solution for runtime resolution):
http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx
When using dependency injection containers, is there a way to determine at statically that all of your dependencies will be resolved?
The Managed Extensibility Framework (MEF) can do this. There are some best practices that you need to adhere to in order for the analysis to be accurate, but the results are otherwise good.
To analyse a set of assemblies a command-line tool is used - see http://blogs.msdn.com/b/nblumhardt/archive/2009/08/28/analyze-mef-assemblies-from-the-command-line.aspx. This can be run from Visual Studio or a build script in a continuous integration server - http://blogs.msdn.com/b/nblumhardt/archive/2009/09/24/debug-composition-from-within-visual-studio.aspx.
You can do it visually (again over a set of assemblies) using the MefContrib project's Visual MEFX - see http://xamlcoder.com/blog/2010/04/10/updated-visual-mefx/
MEF supports this functionality by being both very declarative (standard attributes for configuration) and by using an underlying composition model that works lazily (it can build the graph without creating any instances... Takes a bit to wrap your head around.)
Short answer: no, it can't be done.
Doing this would require being able to represent all components and their dependencies (the container metadata) as a graph, in order to analyze it. Problem is, the more sophisticated the container, the harder it gets to achieve this. Take for example Windsor. Its numerous extension points make the dependencies too dynamic to be represented as a graph. Lazy component loaders, handler selectors, factories, componentmodel contributors, subresolvers, all participate in the process and they can be arbitrary user code, which makes it impossible to analyze statically.
A static analysis might be feasible for a trivial container, but then this hypothetical container would be pretty useless for real-world projects.
So as usual it's a trade-off, and the best we can do is have some tests that exercise the actual resolution of all registered components in the container. StructureMap has a AssertConfigurationIsValid() method to do just that.
Even so, there could be more subtle errors that are not caught by this, such as lifestyle issues.
In addition to what Mauricio said, Windsor 2.5 has a feature that you might find useful when diagnosing issues with missing dependencies or just looking through the components in the container.
I blogged about beta version of it here. It's now quite more useful and as everything in Windsor - it's extensible so you can out your own items on that list.
Maybe not with a dependency injection container. However, you can do dependency injection manually, without a container. For example:
var foo = new Foo();
var bar = new Bar(foo);
var program = new Program(bar);
program.Run();
If it compiles then all the dependencies are there.
However, trouble looms as soon as the dependency graph grows large enough that you can't keep it entirely in your head (espcially with some circular dependencies thrown in the mix). If you do refactorings that involve rearranging of dependencies, then it will become hard work to adapt the order of constructor calls.

Visual Studio: What approach do you use to 'template' plumbing for similar projects?

When building ASP.NET projects there is a certain amount of boilerplate, or plumbing that needs to be done, which is often identical across projects. This is especially the case with MVC and ALT.NET approaches. [I'm thinking of things such as: IoC, ORM, Solution structure (projects), Session Management, User Management, I18n etc.]
I would like to know what approach you find best for 'reusing' this plumbing across projects?
Have a 'master solution' which you duplicate and rename somehow? (I'm using a this to a degree at the moment, but it's fairly messy. Would be interested how people do this 'better')
Mainly rely on Shared Library projects? (I find this appropriate for some things, but too restrictive for things that have to be customised)
Code generation tools, such as T4? (Similar to the approach used by SharpArchitecture - have not tried this myself)
Something else?
Visual Studio supports Custom Templates.
I definitely (mostly!) go for T4 templates in conjunction with a modified version of SubSonic 3. I kind of use the database to model my domain and then use the T4 templates to generate the model and associated controllers and views. It takes about 50-60% of the effort out and keeps a consistency in place.
I then work on overrides (partials) of the classes along with filters and extension methods to 'make the app'. Now that I'm familiar with the environment and what I'm doing, I can have a basic model with good plumbing in place in a very short space of time. More importantly, because I create a set of partial class files, I can regenerate all I want without losing any of my 'custom' coding.
It works for me anyway :)
You could do it the bearded, t-shirted, agile style and create a nice template and put it in sourcecontrol. So when you need a new project, you just checkout the template?
For insanely fast MVC site setup, I use modified T4 templates (created with T4 Editor) and with ALOT of help from Oleg Sych's blogs for page generation (for your typical add/edit/index pages) combined with an awesome implementation of an automated create-update-delete called MVCCrud (if LINQ-to-SQL is your preferred data access method)
Using modified T4 templates and MVCCrud you can create fully functional entities (Create/Edit/List/Delete) with error handling and intuitive error messages in about 4 minutes for each.
I create a new project using the new project wizard so that I get unique project GUIDs assigned. Then I would use "Add Existing Item" to copy items from similar projects if it made sense to do so.
I sometimes use a file diff tool to copy references from one project to another, otherwise I just add the references by hand. A file diff tool can also be used to include similar source files, but the underlying files have to be copied anyway, so I prefer "Add Existing Item".
I've used T4 to generate solution and project files, but that definitely seems like an edge case and not something that would normally be necessary. In that case, I'd probably wrap the T4 in a PowerShell like script to create and populate the rest of the directory structure.
I use "shared libraries" pretty aggressively in general, but not specifically due to this scenario.
In general, I don't find myself reusing plumbing between projects much. It's probably more often that I hack away in one "prototype" project, then abandon it, and rebuild the project from scratch following the above approach and only bring over the "non-hacky" code.
I'm creating a MVC2 application template at http://erictopia.com. It will contain all the basic items I think should be in a MVC project. These include BDD specifications, an ORM (NHibernate and possibly Lightspeed), T4 templates, custom providers, ELMAH support, CSS/Javascript minifier, etc.

Resources