ReSharper 3.1 Released
I am back, after a pause for the flu and the Christmas whirlwind tour.
Jetbrains has released ReSharper 3.1. Although it does not contain the C# 3.0 functionality, it does contain some speed increases. Release notes can be found here.
If you have recently purchased 3.0, this is a free upgrade. If you haven’t purchased 3.0, purchasing this release will give you a free upgrade to 4.0 when it is released.
I highly recommend this add-in for Visual Studio.
Tags: Visual Studio, ReSharper
Ease Versioning Multiple Assemblies by Splitting Up AssemblyInfo
Most .Net project deployments are made up of multiple assemblies and it is common to version all assemblies in a given release with the same version numbers. Since changing each AssemblyInfo.cs file can be time consuming and error prone, most projects take one of two approaches to solving the problem:
- Generate AssemblyInfo.cs files using an nant build scripts and setting properties.
- Use a single AssemblyInfo file and have all projects reference that file.
Both approaches have pluses and minuses. Generating AssemblyInfo.cs can be hard to setup and get correct but is more flexible. Using a single AssemblyInfo.cs and have each project reference it is easier but all projects will have the same information in the assembly properties.
A hybrid approach that many developers overlook is splitting AssemblyInfo.cs into an assembly specific version and a product wide version. Each Visual Studio project would contain the standard AssemblyInfo.cs file that is generated by the project templates. The difference would be that product wide attributes are removed. See the sample AssemblyInfo.cs file below for an assembly named ClassLibrary1.dll:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ClassLibrary1")]
[assembly: AssemblyDescription("Assembly for ClassLibrary1")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e96237d4-2420-4dc7-aed2-43a121bd0221")]
Notice that several of the standard attributes have been removed. Those attributes are moved to a file in a central directory so that it can be changed once for several projects. The following is the contents of a sample file containing these attributes, named ProductAssemblyInfo.cs:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyCompany("My Company")]
[assembly: AssemblyProduct("My Product")]
[assembly: AssemblyCopyright("Copyright © 2007")]
[assembly: AssemblyTrademark("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
After creating the product level AssemblyInfo, multiple VS.net projects can reference it and pull in those attributes. Below is a snapshot of my Solution Explorer within VS.net 2005. Each project has their own AssemblyInfo.cs but each also has a reference to ProductAssemblyInfo.cs. Once the solution is rebuilt, each assembly will have the combination of the attributes in ProductAssemblyInfo.cs and the specific AssemblyInfo.cs.
This approach allows each assembly to have a separate AssemblyTitle, AssemblyDescription, GUID, and ComVisible Setting, while maintaining the ability to change the version numbers and company information in one place and have all assembly builds pick up the updated attributes.
If you are using a continuous integration server like CruiseControl.net, a build dependency can be set on the directory containing ProductAssemblyInfo.cs for each individual build in your product deployment. That way, the entire product will rebuild automatically with new version numbers after ProductAssemblyInfo.cs has been modified.
Tags: cruisecontrol.net, .net, c#, versioning, builds, deployment
ASP.net MVC, MVCContrib, and Using Spring.net as a Controller Factory
The ASP.net MVC CTP as been out for a few days and I have read quite a number of good posts about using the framework and extending the available functionality. Keep an eye on the MVCContrib project over on CodePlex. I can already see that many good things are going to come from this project, based on the functionality already being worked on. There is already integration with the popular Dependency Injection (DI) containers including Windsor, StructureMap, and Spring.net (my contribution to the project). For fans of Resharper, like myself, there will be some live templates developed to help with the normal programming tasks for ASP.net MVC projects.
For this post, I will be discussing the usage of the SpringControllerFactory and how it integrates with ASP.net MVC.
ASP.net MVC has the concept of a Controller Factory (IControllerFactory) that is used to create controller instances. Developers can create their own IControllerFactory implementations to take advantage of class factory implementations already in use or DI/IoC containers like Spring.net. SpringControllerFactory is the IControllerFactory implementation that is included with MVCContrib. Getting started with using this controller factory is easy. Below is a repeat of the brief documentation that I created on the MVCContrib Wiki for SpringControllerFactory, with some additional commentary.
First, you will need to add a reference to MVCContrib.Spring.dll to your project. After adding the reference, you need to add some code to the Global.asax.cs file in your MVC application project to Configure the controller factory and tell the MVC framework about it.
protected void Application_Start(object sender, EventArgs e)
{
//This example just sets the default context for
//use with the Spring.net Controller
//Factory. An IObjectFactory instance is also
//supported, if greater control over
//Spring.net is desired.
IApplicationContext ctx = ContextRegistry.GetContext();
SpringControllerFactory.Configure(ctx);
ControllerBuilder.Current.SetDefaultControllerFactory(
typeof(SpringControllerFactory));
//more configuration code for the MVC framework
}
The code above retrieves the default Spring.net context and passes it to the static Configure() method on SpringControllerFactory. Configure() will accept either an IObjectFactory instance or an IApplicationContext instance. Spring.net documentation recommends the IApplicationContext approach for most cases. IObjectFactory implementations allow for greater flexibility when you need it. This step is necessary to allow the developer to share the Spring.net context with the controller factory and any other components there might be in the application. In other words, this allows a singleton to really be a singleton for the entire appdomain. Since currently there is no way to pass an instance of a controller factory to ControllerBuilder (notice that SetDefaultControllerFactory() accepts a Type), somewhat ugly approaches need to be taken to share state between controller factories and other components.
Some will probably not like the approach I took with the static Configure() method. I went with the static method approach because I thought it was the most strait forward way of communicating to developers what needs to happen before the controller factory is used. The developer of the Windsor controller factory implementation for MVCContrib took the approach of requiring the developer to extend the HttpApplication to implement the Windsor IContainerAccessor interface. I really like this implementation but Spring.net does not really have the equivalent concept so I went with the simple static method approach.
The instances of IController that you create for your application now need to be configured in Spring.net. Note that the object name for the IController instances need to be the Type.Name of each particular instance. This isn’t really a great approach either, but like SetDefaultControllerFactory(), IControllerFactory.GetController() only accepts a Type parameter. Phil Haack said they are looking into possibly changing this. Phil, can you guys also look into allowing developers to pass an instance of IControllerFactory to the ControllerBuilder as well? Pretty please?
Below is a shell of an IController implementation that I used for the unit testing of SpringControllerFactory and the configuration that would go along with it.
public class SimpleController : IController
{
public void Execute(ControllerContext controllerContext)
{
//controller code goes here
}
}
<objects xmlns="http://www.springframework.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">
<object id="SimpleController" singleton="true" type="Examples.SimpleController"/>
</objects>
I am working on a full working sample application that uses Spring.net for the controller factory. That sample will be included in the MVCContrib source tree as well and should be there soon.
Tags: mvc framwork, mvc, asp.net, asp.net mvc, spring.net, controller factory, mvccontrib
ASP.Net 3.5 Extensions (MVC Framework) Preview is Out
I first read the news from Brad Abrams, but there are several links in my rss reader this morning.
Microsoft has released the preview of ASP.NET 3.5 Extensions, which includes the much anticipated (at least by me) MVC framework. Also included are Astoria, which is apparently officially named ADO.NET Data Services, better data controls, and more Silverlight goodness as well as other things.
The download is available here.
Tags: asp.net, mvc, c#, astoria
Are Extension Methods Useful for Normal Programming Tasks?
With the release of Visual Studio 2008, Microsoft also released C# 3.0. The new language version includes some nice programmer productivity features like Anonymous Properties, Lamda Expressions, and Extension Methods. I will be concentrating on Extension Methods for this post.
Extension methods allow a programmer to define a set of static methods in a static class that can be called on any object that matches the parameter type of the method. Note that the methods must be in a static class or they may not be used as Extension methods. For instance, I have defined the following static class named SampleExtension:
The only difference between ExtMethod1() and any other static method is the use of the keyword this. The use of this string is basically saying that the Extension Method ExtMethod1() can operate on any object of type string and that the string itself should be passed to the method as a parameter.
To use my new Extension Method, all I need to do is import the StringExtensions namespace and start calling the new method on string data types.
As you can see, Extension Methods make a class appear to have new methods that are not in the original class definition. Visual Studio will even give you Intellisense for the Extension Methods in the namespaces you are referencing.
Some of the dynamic languages, like Ruby for instance, have included this type of functionality for quite some time. In fact, the Ruby on Rails framework makes extensive use of this type of functionality. LINQ, new to .Net 3.5, utilizes Extension Methods to all developers to incorporate their collection types directly in the syntax of the queries.
Well printing to the console is nice, but not very useful in real life. The method below demonstrates create an object instance based on string representation of the object type:
Below, I have added an example of calling this method.
The final aspect of Extension Method syntax I wanted to discuss is that, just like other static methods, Extension Methods may accept other parameters in addition to the object that is targeted for extension. Below I have added a new overload to ExtMethod1() that accepts an additional string parameter:
Calling the method overload is just like calling any normal method:
Finally, developers might be tempted to put these extension methods operating on System.* types under the System namespace, thinking that it is more convenient for users of their methods. I believe you should refrain from this and instead keep your Extension Methods in specialized namespaces. This will keep users of your libraries from inadvertently using your methods when they do not intend to. After all, every C# class imports the System namespace automatically.
In my opinion, Extension Methods are probably most useful for framework and reusable library development. Now that Visual Studio 2008 is officially released, C# 3.0 will start gaining more usage, and we will see how people use this new capability.
I hope you find this brief introduction to Extension Methods useful. You can find the sample code here.
Tags: c#, .net, c# 3.0, extension methods
Dependency Injection – Good for more than just unit testing.
I read the article on InfoQ about the various blog posts that have been going back forth concerning the pros and cons of Dependency Injection (DI).
A very interesting read for certain. I think there are excellent points made on both sides. Ultimately, there are pluses and minuses to all software architecture decisions. I believe that if someone doesn’t think that tradeoffs exist in their architecture, they likely do not understand software architecture very well.
Jacob Profit argues that DI has grown in popularity largely because it helps with Test Driven Development (TDD). Certainly, DI helps dramatically in this area and it likely is a good reason for the popularity surge. However, I don’t really agree with his assessment of how the caller becomes responsible for configuration of dependencies when implementing DI. Well, let me restate that to: It can be that way but it certainly doesn’t have to be and I highly recommend against it.
First, using a framework makes things much easier. The choice of framework makes a difference. DI frameworks come in 2 basic flavors: file based configuration and code based configuration. A few support both configuration methods but most fall into one category or the other. In the file based configuration camp, Spring.net is my favorite but there are other excellent choices like Windsor and StructureMap. ObjectBuilder from the MS Patterns and Practices group is an example of a code based configuration DI framework.
In my opinion, a code based configuration DI framework can lead you down the path the Jacob Profit mentioned – making configuration of dependencies the responsibility of the caller.
Just like Oren, I like DI because it makes it easier to create a loosely coupled software architecture. When I use Spring.net, I get the added bonus of the ability to abstract away the location of my components when I use the proxy factories. With Spring.net proxy factories, a dependency could be a local, in process, object instance or a proxy to a remoting object, web service, or enterprise service. The product will soon support WCF as well. This helps me develop and test in an all local configuration and move to a more distributed model after I am sure the core logic works locally in process.
Eli Lopian entered the discussion on the negative side of DI but made some statements that I think are a little misleading:
When you use DI as a ’Silver Bullet’ you are losing more then half the abilities of your programming language. You can not use static methods or the ‘new‘ keyword or sealed types. Oh, you have to make all your methods virtual too. This is going to be even harder once Extension Methods (and Linq) become main stream.
I will concede the static keyword argument. It is difficult to handle static methods in DI frameworks.
The new keyword seems to me to be by design rather than a negative side effect. DI frameworks create and configure dependencies for an object. Therefore, the need to call new is removed.
It is possible Eli was referring to the need for later dependency creation rather than creating all dependencies at startup. I can see this being a requirement. In fact, I have had the requirement myself and I solved it by having the object request the dependency from the Spring.net context rather than having the dependency injected. I realize this is not ideal, but no worse than coupling to a concrete implementation or factory in my opinion.
Eli also says that you cannot use sealed types and all methods must be made virtual. This is where Eli and I start to part ways.
I have used both sealed types in my Spring.net configuration and have used objects without virtual methods. In fact, most of my objects do not have virtual methods. Whether or not to make a class sealed and make methods virtual is a design decision that has nothing to do with the use of a DI container. I make sure to retain the flexibility of the caller by enforcing the use of the interface/implementation paradigm in my designs. This way I can divorce my decisions about inheritability from the flexibility I want in the caller’s code. I agree that you probably want to avoid sealed classes and make methods virtual, if the caller is declaring concrete class variables instead of interfaces. However, interfaces are the way to go in my opinion. In fact, using interfaces for variable declaration types is a good idea in many cases even if a DI container is not used at all.
I might be missing the point but the last sentence in the quote from Eli Lopian does not make since to me at all. Using extension methods is perfectly ok with DI containers. I have even attached a very simple sample project to this post demonstrating both calling extension methods from an object returned from the Spring.net context, and calling extension methods on a property injected within the container. I fail to see why LINQ would be a big issue either. The types of objects I would be performing LINQ queries on would likely be value objects that I use for my problem domain. These would not be something I would normally configure in a DI container anyway.
By the way, I am already working on a post describing Extension Methods in general and I should be posting that either tomorrow or Monday.
Tags: spring.net, dependency injection, unit testing, tdd, extension methods, c#
New Property Syntax for C# 3.0
C# 3.0 has many new features that have been widely discussed. LINQ is likely the most talked about language feature in the new version. One feature that does not seem to be getting much attention is the new syntax for defining properties. I have seen this referred to as Anonymous Properties, although I am not sure that this is the official name.
I think this is actually going to be one of my favorite language features going forward and it is certainly long overdue. Anonymous Properties allows the developer to define a variable and make it available as a property, all in statement. Traditionally, a class with properties is defined as follows:
public class SampleProperties
{
private string firstName;
private string lastname;
public string FirstName
{
get {return firstName;}
set {firstName = value;}
}
public string LastName
{
get {return lastName;}
set {lastName = value;}
}
}
The above code pattern is recognizable for anyone who has been writing C# at all. Admittedly, it is not a complicated syntax and I much prefer it over the java getter/setter bean pattern. However, Microsoft has added an even more compact syntax for those situations where nothing needs to happen for property getters and setters except the manipulation of the instance variable they wrap:
public class SampleProperties
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
Much better!
Tags: c#, .net, c# 3.0, properties, anonymous properties
What is Dependency Injection (and why you should care)?
There is much discussion around the new ASP.net MVC framework. Scott Guthrie has been writing a series of articles describing the functionality of the upcoming framework. I highly recommend looking at this soon to be released framework offering from Microsoft. One feature that I am happy to see is the ability to integrate the MVC framework with dependency injection containers such as Spring.net and Windsor. I plan to go over this integration capability in a future post but I like to start with a post discussing dependency injection in general.
The central idea behind dependency injection containers, also called Inversion of Control (IoC) containers, is to create flexibility in program architecture by removing the knowledge of dependency creation and configuration from the individual software components. For instance, I have a program that has a customer component whose responsibility is saving and retrieving customer objects. The customer component is a user of the validation component as well as the persistence component. Traditionally, I would have simply created new instances of these services from within my customer component:
public class CustomerComponent {
private ValidationComponent validationComponent;
private PersistenceComponent persistenceComponent;
public CustomerComponent() {
validationComponent = new ValidationComponent();
persistenceComponent = new PersistenceComponent();
}
//use these two components
}
The problem with this implementation is that it ties my customer component to these two concrete implementations of its dependent services. Of course, a better way to this is to use some sort of factory pattern implementation. That code might look like this:
public class CustomerComponent {
private ValidationComponent validationComponent;
private PersistenceComponent persistenceComponent;
public CustomerComponent() {
validationComponent = MyFactory.Get("Validation");
persistenceComponent = MyFactory.Get("Persistence");
}
//use these two components
}
This is much better than the first block of code because I am no longer tied to the concrete implementations, provided that ValidationComponent and PersistenceComponent are abstract implementations. However, I am tied to the MyFactory class implementation. This is where a dependency injection framework comes to the rescue. A dependency injection container allows me to define properties in my customer component class for each of the dependent components I need. When the container creates an instance of my customer component, those dependency properties I have created are automatically set with fully configured implementations. In the code below, the CustomerComponent implementation has properties for the validation and persistence components, but no code to set these properties:
public class CustomerComponent {
private ValidationComponent validationComponent;
private PersistenceComponent persistenceComponent;
public ValidationComponent Validation {
get {return validationComponent;}
set(ValidationComponent value) {validationComponent = value;}
}
public PersistenceComponent Persistence {
get {return persistenceComponet;}
set(PersistenceComponent value) {persistenceComponent = value;}
}
//use these two components
}
If I am using C# 3.0, I can take advantage of the new property syntax and my class will trim down some:
public class CustomerComponent {
private ValidationComponent validationComponent {get;set;}
private PersistenceComponent persistenceComponent {get;set;}
//use these two components
}
The dependency injections frameworks will all vary slightly on what happens from here but they all have a lot in common. Spring.net, Windsor, and StructureMap all have xml configuration files that allow you to specify the .Net System.Type and give a name to each of your components. They also have the ability to set properties on your components, or even set private field values in certain cases. The values of these properties can be standard .Net data types or they can also be other objects that have configured in the container.
This was a very brief introduction to the concept of dependency injection and I am planning to write up more detailed descriptions on the details of using Spring.net, Windsor, and StructureMap soon.
Tags: dependency injection, asp.net mvc, spring.net, windsor