I want to show a quick way of adding FluentNHibernate into your project.
First make sure you have NuGet installed in VS 2010. You can find it in the Extension Manager.
Now you can use the View->Other Windows-> Package Managere Console and write
nuget Install-Package FluentNHibernate
This command automatically retrieves the latest version of FluentNHibernate from nuget.org with all its dependencies.
Next you’ll have to start configuring FluentNHibernate, have a look at the tutorial found at http://wiki.fluentnhibernate.org/Getting_started.
Enjoy
In this post I want to highlight how easy it is starting a MVC Project using NuGet and deploy it to AppHarbor. It is not much but it is fun.
First you need to install Visual Studio 2010. Then, go to Tools –> Extension Manager. From the Online Galery install NuGet ( if you don’t already have it ). Make sure you also have ASP.NET MVC3 installed.
Create a new MVC 3 Project. Add a Class Library project to the solution.
Since you’ve added NuGet you have access to the Package Manager Console. I’m sure there might be other ways but what I do is this: I select Test from the Default project in the toolbar.
Type the following command
Install-Package NUnit
This is will add the latest NUnit release. Should you want you can also add Machine.Specifications.
What would an MVC Project be without an IoC/DI container. So you should add your favourite, I usually go for Unity.
Test your app by pressing F5.
Now for the fun part. Create an account with AppHarbor. Install Git if you didn’t already.
Create an application in AppHarbor and follow their instructions. Push the application to the url AppHarbor gave you. Review the Build status. It might be that the app is not yet deployed to their nginx server so you might have to wait a while, for me it was about 2 minutes.
After the wait I saw the app running so now I can continue with my development.
Give it a go!
I blogged a while ago about creating a series of posts on building an ASP.NET MVC application. To be honest I had already built one. It took me three months. And I haven’t touched it for about two months, so I thought at least I can share it with you geek readers.
The main difference between MVC in Rails and MVC in ASP.NET is that Rails generates the infrastructure from the commands you type, as for the ASP.NET MVC part you are responsible for building the infrastructure.
What do I mean when I say infrastructure? Well basically all the plumbing that goes into accessing the database, talking to services, generating rss content etc.
What is Universum? It’s meant to be a community web site where teachers and students can collaborate. And it’s a basic framework on which you can develop applications that are based on article publishing. I am only interested in sharing the code with you, if it helps you good, if not.. well no harm no fowl.
That’s about all the talk, if you have the time please review it and tell me if it can walk the walk.
The application provides simple management for blogs, resources, questions, courses. There are areas where I could improve it, but I no longer have the time.
A bit of info on the database. I decided to use Db4objects. It was pretty nice to tell you the truth, but I hope the Repository pattern I found and used is good enough to accommodate different implementations.
User roles. If you are not authenticated then you are considered an anonymous user and don’t have access to nothing except the main page.
An authenticated user can be – one special user that can register students and teachers, a student or a teacher.
Determining if a user is a student or a teacher is done via regular expression ( that’s how student names are configured at my faculty ). The implementation is easy to change however so that is not a problem.
Indexing articles is done through Lucene.NET. I have to say I had a lot of problems with it, and I’m not sure I solved them all.
Not much testing, there was no time. Usually I have confidence in my coding style, and I tried getting as many things in as possible in a short amount of time.
The project was built as part of my bachelor degree, and I have to admit I whished I didn’t do so much, since in the end it didn’t even matter, 20 minutes to rate three months of work is hard to fit.
If enough people find it interesting I’ll blog about the parts of the application some more, until then download the source code from codeplex, and log in with secretary / asdf1234qwer. In the web.config you can set up the paths the project requires on disk, the sample uses C:\Universum. Also I recommend having IIS7.
Hello, this is the 6th part of the IoC Containers series. This is the last container I’ll explore. I’ve been using it at work because it’s got the “Made by Microsoft” insignia and it seems the policy is that anything done at Microsoft is good for use. Bet that happens to you also.
I’ve downloaded what I hope is the latest version from codeplex.
Our Bootstrapper code is now
public class Bootstrap
{
public static IUnityContainer Components()
{
IUnityContainer container = new UnityContainer();
container.RegisterType<IClearScreen,
ConsoleClearScreen>(
new ContainerControlledLifetimeManager());
container.RegisterType<IWriteString,
ConsoleWriteString>(
new ContainerControlledLifetimeManager() );
container.RegisterType<IFunctionState,
AlarmFunctionState>("Alarm");
container.RegisterType<IFunctionState,
NewLineFunctionState>("NewLine");
container.RegisterType<IFunctionState,
CalculatorFunctionState>("Calculator");
container.RegisterType<IConsoleInputService,
ConsoleInputServiceImpl>(
new ContainerControlledLifetimeManager() );
return container;
}
}
The ContainerControllerLifetimeManager is Microsoft’s way of saying this is a singleton instance. If we don’t specify nothing then a new instance will be created always.
The service retrieve through a simple call to container.Resolve<TInstance>.
The container also supports xml configuration.
Next we’ll se how our App.config file looks like
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity>
<typeAliases>
<!-- Lifetime manager types -->
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
</typeAliases>
<containers>
<container>
<types>
<type
type="IoCContainers.Components.Services.IWriteString, IoCContainersUnity"
mapTo="IoCContainers.Components.Services.ConsoleWriteString, IoCContainersUnity">
<lifetime type="singleton" />
</type>
<type
type="IoCContainers.Components.Services.IClearScreen, IoCContainersUnity"
mapTo="IoCContainers.Components.Services.ConsoleClearScreen, IoCContainersUnity">
<lifetime type="singleton" />
</type>
<type name="Alarm"
type="IoCContainers.Components.Functions.IFunctionState, IoCContainersUnity"
mapTo="IoCContainers.Components.Functions.AlarmFunctionState, IoCContainersUnity" />
<type name="NewLine"
type="IoCContainers.Components.Functions.IFunctionState, IoCContainersUnity"
mapTo="IoCContainers.Components.Functions.NewLineFunctionState, IoCContainersUnity"/>
<type name="Calculator"
type="IoCContainers.Components.Functions.IFunctionState, IoCContainersUnity"
mapTo="IoCContainers.Components.Functions.CalculatorFunctionState, IoCContainersUnity"/>
<type
type="IoCContainers.Components.Services.IConsoleInputService, IoCContainersUnity"
mapTo="IoCContainers.Components.Services.ConsoleInputServiceImpl, IoCContainersUnity">
<lifetime type="singleton" />
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,Microsoft.Practices.Unity.Configuration">
<constructor>
<param name="functionStates" parameterType="IoCContainers.Components.Functions.IFunctionState[], IoCContainersUnity">
<array>
<dependency name="Alarm"/>
<dependency name="NewLine"/>
<dependency name="Calculator"/>
</array>
</param>
</constructor>
</typeConfig>
</type>
</types>
</container>
</containers>
</unity>
</configuration>
You won’t escape that easy though, you still need to tell the bootstraper to configure the container like this
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)
ConfigurationManager.GetSection( "unity" );
section.Containers.Default.Configure( container );
Hope this is usefull. This is the final IoC Container I wanted to explore with you reader, in the next article I’ll try to lay out some general feelings about this containers.
The code can be donwloaded from codeplex.
Hi, this is part 5 of our series on IoC containers in .NET. I’m only using them on a simple console application that provides autocompletion for the functions that the application exposes.
We started with an introductory article, then we used Autofac, StructureMap, Ninject 2 beta and Spring.NET.
In this article I’ll cover CastleWindsor a bit. These files can be found on sourceforge at the following address http://sourceforge.net/projects/castleproject/files/InversionOfControl/.
Like StructureMap it can be configured through code or from an xml configuration. I’ll first show the way to configure the app from code than I’ll go for the xml configuration option.
Using the configuration from code looks like this:
public class Bootstrap
{
public static IWindsorContainer Components()
{
WindsorContainer wc = new WindsorContainer();
wc.AddComponentLifeStyle<IWriteString,
ConsoleWriteString>(
Castle.Core.LifestyleType.Singleton );
wc.AddComponentLifeStyle<IClearScreen,
ConsoleClearScreen>(
Castle.Core.LifestyleType.Singleton );
wc.AddComponent<IFunctionState,
AlarmFunctionState>();
wc.AddComponent<IFunctionState,
NewLineFunctionState>();
wc.AddComponent<IFunctionState,
CalculatorFunctionState>();
wc.AddComponentLifeStyle<IConsoleInputService,
ConsoleInputServiceImpl>(
Castle.Core.LifestyleType.Singleton );
return wc;
}
}
As Jan Stenberg pointed out, there is a better way of configuring the container and it looks like this
WindsorContainer wc = new WindsorContainer();
wc.Register( Component.For<IWriteString>()
.ImplementedBy<ConsoleWriteString>()
.LifeStyle.Singleton )
.Register( Component.For<IClearScreen>()
.ImplementedBy<ConsoleClearScreen>()
.LifeStyle.Singleton )
.Register(Component.For<IFunctionState>()
.ImplementedBy<AlarmFunctionState>())
.Register(Component.For<IFunctionState>()
.ImplementedBy<NewLineFunctionState>())
.Register(Component.For<IFunctionState>()
.ImplementedBy<CalculatorFunctionState>())
.Register(Component.For<IConsoleInputService>()
.ImplementedBy<ConsoleInputServiceImpl>()
.LifeStyle.Singleton)
;
You get the container like so
var kernel = Bootstrap.Components();
And the thing I kind-a struggled with is that in order to construct my service I had to declare a dictionary
var parameters = new Hashtable();
parameters.Add( "functionStates",
kernel.ResolveAll<IFunctionState>() );
And pass it in when I resolved the service
var shortcutService = kernel.Resolve<IConsoleInputService>(parameters);
The fact the you have to specify the parameters outside the bootstrapping is a small inconvenient but we can live with it.
The xml part is a bit more simple to comprehend an it’s what you’ll prefer to use in most applications.
Now the Bootstrap class looks like this
public class Bootstrap
{
public static IWindsorContainer Components()
{
WindsorContainer wc = new WindsorContainer( new XmlInterpreter() );
return wc;
}
}
And we got the service resolution down to
var shortcutService = kernel.Resolve<IConsoleInputService>( );
Niiice, isn’t it? As always the source can be found at this adress.
Hi, nice to have you read this again. This is part 4 of the series I’m doing on the existing .Net IoC Containers that I found interesting. After a brief introduction of what is an IoC in my option, I presented Autofac,,StructureMap and Ninject2.
In this post we’ll be exploring the Spring.NET IoC container. This is a xml configurable IoC by design. I’m using the latest version of it Spring.NET 1.3 RC1, hopefully it’s stable enough and that it brings something new to the table, by new I mean it uses the .NET 3.5 capabilities.
You can get the latest version of Spring.NET from http://www.springframework.net/. You will probably have to complete some kind of a registration form. I know I did.
Before you read any further I have to warn you that Spring.NET is a beast in the sense that is hard to configure and I don’t recommend using it.
Just as you would have done in Java once you get the configuration part out of the way it gets easier to use this framework. There is however a gotcha, after you get a valid IApplicationContext you are forced to use “magic strings” in your program to get to certain registered instances. You could probably define your own wrapper over the default registry methods, but that’s something you should explore on your own.
Let’s see how everything worked out. First I got the instance of the IApplicationContext using the line below:
IApplicationContext appContext = ContextRegistry.GetContext("spring.root");
I also configured the App.config file like so:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net">
<description>Definitions of objects to be exported.</description>
<object id="WriteString"
type="IoCContainers.Components.Services.ConsoleWriteString, IoCContainersSpringNET" />
<object id="ClearScreen"
type="IoCContainers.Components.Services.ConsoleClearScreen, IoCContainersSpringNET" />
<object id="Alarm"
type="IoCContainers.Components.Functions.AlarmFunctionState, IoCContainersSpringNET" >
<constructor-arg name="clearScreen">
<ref object="ClearScreen"/>
</constructor-arg>
<constructor-arg name="writerString">
<ref object="WriteString"/>
</constructor-arg>
</object>
<object id="NewLine"
type="IoCContainers.Components.Functions.NewLineFunctionState, IoCContainersSpringNET" >
<constructor-arg name="clearScreen">
<ref object="ClearScreen"/>
</constructor-arg>
<constructor-arg name="writeString">
<ref object="WriteString"/>
</constructor-arg>
</object>
<object id="Calculator"
type="IoCContainers.Components.Functions.CalculatorFunctionState, IoCContainersSpringNET" >
<constructor-arg name="clearScreen">
<ref object="ClearScreen"/>
</constructor-arg>
<constructor-arg name="writeString">
<ref object="WriteString"/>
</constructor-arg>
</object>
<object id="ConsoleInput"
type="IoCContainers.Components.Services.ConsoleInputServiceImpl, IoCContainersSpringNET" >
<constructor-arg name="functionStates">
<list>
<ref object="Alarm"/>
<ref object="NewLine"/>
<ref object="Calculator"/>
</list>
</constructor-arg>
</object>
</objects>
</spring>
</configuration>
Word of caution: The context part of the configuration is mandatory, it will through an error otherwise. The objects section however is referenced in the spring/context using the resource uri=”..” tag
Very disappointing to me was the fact that I had to use the IApplicationContext instance I got from the ContextRegistry like this to get my object instance:
var shortcutService = appContext.GetObject( "ConsoleInput" ) as IConsoleInputService;
One other thing I believe that by default the objects are configured using a Singleton behaviour. I didn’t use this library much outside the Java environment, and I have to say I like the .NET IoC’s that we’ve explored way better than this approach.
On the other hand there is a lot more to Spring than this, so as an enterprise middleware IoC Container it probably shines but that is for you to decide.
As always as posted the source code on codeplex and you can download it here.
I wanted to use Ninject 1.0 but I discovered that it didn’t support named binding, and didn’t know how to resolve multiple bindings to an array.
Luckily I found the Ninject 2 post it’s way better than the previous version, and the changes were almost a no brainer.
Hy, this continues the series of posts on IoC Containers in .NET. We are using these continers on a simple console application that autocompletes it’s functions. I’m mostly displaying the configuration part of the IoC, an overview of this tools will follow after we’ll have explored enough of them.
After a brief introduction of what is an IoC, I presented Autofac, and StructureMap.
In this post we’ll explore the Ninject 2 beta IoC that you can download at http://kohari.org/2009/02/25/ninject-2-reaches-beta/.
One thing that Ninject tries to do is free you from having to write an xml configuration file, that means it does not have support for such a configuration type, instead it comes with another nice fluent api.
What I do like about ninject it that it has support for .NET Compact Framework. I’m mentioning this because I had the occasion of writing an app for .NET CF and it helped me a lot. AFAIK this is the single IoC in .NET that has this support.
Instead of a container Ninject uses the notion of a kernel. Another difference is that it requires you to build modules, so I used the Bootstrap as a module, and the Components method returns the IKernel instance.
I didn’t explore the new Ninject deeply I was just happy I could get the application running.
So our Bootstrap class looks like this
public class Bootstrap : Module
{
public static IKernel Components()
{
IKernel kernel = new StandardKernel( new Bootstrap() );
return kernel;
}
public override void Load()
{
Bind<IWriteString>()
.To<ConsoleWriteString>()
.InSingletonScope();
Bind<IClearScreen>()
.To<ConsoleClearScreen>()
.InSingletonScope();
Bind<IFunctionState>()
.To<AlarmFunctionState>().Named("Alarm");
Bind<IFunctionState>()
.To<NewLineFunctionState>().Named("NewLine");
Bind<IFunctionState>()
.To<CalculatorFunctionState>().Named("Calculator");
this.Bind<IConsoleInputService>().To<ConsoleInputServiceImpl>();
}
}
Don’t know about you but I like it. Obviously the way I get these values in the Program.cs changed as in the other posts but I didn’t expose that change.
Since Ninject doesn’t provide a Xml configuration you’re stuck with a codebase that nees to be recompiled, luckily that should not take to much.
As always the code can be downloaded here.
In our first part of the series we saw what Autofac had to offer us in order to get the simple console application that provides code completion capabilities.
In this part I’ll use StructureMap and we’ll see how this product does.
First let’s download it from http://sourceforge.net/projects/structuremap/files/. The latest version is StructureMap2.5.3.
StructureMap is configured through a static ObjectFactory class. Usually you end up creating such a global class yourself, at least it comes already bundled with it.
Because StructureMap uses the ObjectFactory class for initialization as well as object retrieval our Bootstrapper now looks like this.
public class Bootstrap
{
public static void Components()
{
ObjectFactory.Initialize( container =>
{
container
.ForRequestedType<IClearScreen>()
.TheDefaultIsConcreteType<ConsoleClearScreen>()
.AsSingletons();
container
.ForRequestedType<IWriteString>()
.TheDefaultIsConcreteType<ConsoleWriteString>()
.AsSingletons();
container.ForRequestedType<IFunctionState>().AddConcreteType<AlarmFunctionState>();
container.ForRequestedType<IFunctionState>().AddConcreteType<NewLineFunctionState>();
container.ForRequestedType<IFunctionState>().AddConcreteType<CalculatorFunctionState>();
container.ForRequestedType<IConsoleInputService>().AsSingletons()
.TheDefault.Is.OfConcreteType<ConsoleInputServiceImpl>()
.WithCtorArg( "functionStates" ).EqualTo(
ObjectFactory.GetAllInstances<IFunctionState>()
);
} );
}
}
On thing you will absolutely notice is that the way we configure it has changed, but it still uses a fluent interface for configuration. One other thing is that it nows to resolve registered instances into an array that can be injected with a constructor argument.
Next I’ll show the same Bootstrapper, but instead of defining it in code I’ll move the part I expect to change into an xml.
public class Bootstrap
{
public static void Components()
{
ObjectFactory.Initialize( container =>
{
//container
// .ForRequestedType<IClearScreen>()
// .TheDefaultIsConcreteType<ConsoleClearScreen>()
// .AsSingletons();
//container
// .ForRequestedType<IWriteString>()
// .TheDefaultIsConcreteType<ConsoleWriteString>()
// .AsSingletons();
//container.ForRequestedType<IFunctionState>().AddConcreteType<AlarmFunctionState>();
//container.ForRequestedType<IFunctionState>().AddConcreteType<NewLineFunctionState>();
//container.ForRequestedType<IFunctionState>().AddConcreteType<CalculatorFunctionState>();
container.PullConfigurationFromAppConfig = true;
container.ForRequestedType<IConsoleInputService>().AsSingletons()
.TheDefault.Is.OfConcreteType<ConsoleInputServiceImpl>()
.WithCtorArg( "functionStates" ).EqualTo(
ObjectFactory.GetAllInstances<IFunctionState>()
);
} );
}
}
The PullConfigurationFromAppConfig flag tells structure map to read the configuration file.
Caution: I had to move the IClearScreen and IWriteString to the config file as well since it doesn’t know how to configure the IFunctionState items otherwise.
For this simple example I used the App.config file, you can however configure everything in a StructureMap.xml located in the same directory you would normally put your App.config.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="StructureMap" type="StructureMap.Configuration.StructureMapConfigurationSection,StructureMap"/>
</configSections>
<StructureMap defaultAssembly="IoCContainers">
<DefaultInstance
PluginType ="IoCContainers.Components.Services.IWriteString, IoCContainersStructureMap"
PluggedType ="IoCContainers.Components.Services.ConsoleWriteString, IoCContainersStructureMap"
Scope="Singleton" />
<DefaultInstance
PluginType ="IoCContainers.Components.Services.IClearScreen, IoCContainersStructureMap"
PluggedType ="IoCContainers.Components.Services.ConsoleClearScreen, IoCContainersStructureMap"
Scope="Singleton" />
<AddInstance Key="Alarm"
PluginType ="IoCContainers.Components.Functions.IFunctionState, IoCContainersStructureMap"
PluggedType ="IoCContainers.Components.Functions.AlarmFunctionState, IoCContainersStructureMap" />
<AddInstance Key="NewLine"
PluginType ="IoCContainers.Components.Functions.IFunctionState, IoCContainersStructureMap"
PluggedType ="IoCContainers.Components.Functions.NewLineFunctionState, IoCContainersStructureMap" />
<AddInstance Key="Computer"
PluginType ="IoCContainers.Components.Functions.IFunctionState, IoCContainersStructureMap"
PluggedType ="IoCContainers.Components.Functions.CalculatorFunctionState, IoCContainersStructureMap" />
</StructureMap>
</configuration>
Now we can change values without recompiling the application, this however is error prone, and does not handle class renames to lightly. It’s not big of a deal if you think of it since you know you have it configured so when you rename a class you’ll know to go and rename values from the config file as well.
That was it for know, I’ll choose another IoC for our next post, the code you can get from here.
This is an interesting IoC project that I used in a couple of occasions, nothing big, but I sure enjoyed it immensely.
Autofac is wrist friendly so to speak and it tries to solve your configuration problems in a simple and concise manner.
Without further ado go at http://code.google.com/p/autofac/ to get the latest version.
Next I’ll try to create a simple example that I hope we’ll use for the most part of this series.
In learning the inner workings of IoC containers we’ll develop a console application that provides some simple autocomplete for it’s features.
The features of our application are:
- Autocomplete for internal commands
- Commands
- Alert – displays a message box
- NewLine – goes to the next line
- Calculator – with support for add
All of this features will be organized under the Components folder as functions and services.
In general you will want the concrete classes to be linked to an interface, and is by default the way I like to handle it.
A lot of voices in the community are against the use of xml files for configuration, and to that regard Autofac offers the option of using a fluent interface for configuring the builder. Although good for contracts that you are not likely to change without recompiling the application, when you need to have functionality similar to that of a plug-in you will prefer to use an IoC capable of reading xml configuration. Obviously Autofac has support for xml files as well.
Note xml configuration support is very limited in Autofac, so I’ll only show the bootstraping for this file
As I said earlier an IoC is just a form of factory, the only real difference is that this is a factory with nice configuration capabilities.
In more complex applications I recommend you use modules for configuring but for this example is sufficient to have everything configured in only one place.
As a preference I always configure the IoC I’m using in a class called Bootstrap in my highest level module ( commonly identified as the assembly containing the Main function, or if in a web app the assembly that contains the Global.asax).
The code for the Bootstrap.cs looks like this:
public class Bootstrap
{
public static IContainer Components(){
var builder = new ContainerBuilder();
builder.Register<ConsoleClearScreen>().As<IClearScreen>().SingletonScoped();
builder.Register<ConsoleWriteString>().As<IWriteString>().SingletonScoped();
builder.Register<AlarmFunctionState>().As<IFunctionState>().Named( "AlarmFunctionState" );
builder.Register<NewLineFunctionState>().As<IFunctionState>().Named( "NewLineTransition" );
builder.Register<CalculatorFunctionState>().As<IFunctionState>().Named( "CalculatorTransition" );
builder.Register<IConsoleInputService>(
c => new ConsoleInputServiceImpl(
new IFunctionState[]{
c.Resolve<IFunctionState>("AlarmFunctionState"),
c.Resolve<IFunctionState>("NewLineTransition"),
c.Resolve<IFunctionState>("CalculatorTransition")
} ) );
return builder.Build();
}
}
Autofac uses the ContainerBuilder class to register services and it offers a simple method of directly creating those services through the use of lambda expressions.
For the actual implementation of the app you can download the source code here.