Software Mechanics
Why do we even have that lever?

Unity 2.0 Automatic Factories

January 7, 2010 18:25 by chris

As we’re sloping down the glide path into the release of Unity 2.0 and Entlib 5, I wanted to start talking about some of the things that got added or changed in the container. For this post I want to discuss the new “automatic factories feature.”

This one was a recent addition that I threw in over the Christmas holiday, “inspired” by a feature recently added to AutoFac. At it’s core it answers a simple problem: what if I have to create objects through the container, but I don’t need them at injection time, but later?

This comes up in lots of situations. The object may be heavy, so you don’t want to create it until you absolutely need it. Or you need many of them, but can’t predict when.With Unity 1.2, you basically had two choices in this scenario.

First, you could inject the container as a dependency. This works, but has several issues. You’ve now coupled yourself to the container. Also, you have no way of knowing as a consumer of that class what needs to be in the container – the dependencies have become completely opaque.

A second choice is to inject a factory object. Then call the factory when you need to create an object; the factory implementation can call back into the container. This improves testability and solves the lack of metadata problem above. However, it has the downside of lots of boilerplate code. A separate factory class for every class in your system. Ugh.

Automatic factories solve these problems pretty easily. It’s so simple I should have done it a long time ago. Simply have a dependency of type Func<Whatever>. Then you’ll get that delegate injected. When you invoke the delegate, it calls back into the container to Resolve<Whatever>().

If you resolve the dependency with a name, that’s the name the func will use when invoked to do a resolve.

Finally, if your dependency is Func<IEnumerable<Whatever>>, then you’ll get a ResolveAll call executed.

Simple. straightforward, and solves all the problems of coupling, lack of metadata, and boilerplate code.

This is in the drop I just posted yesterday on Codeplex source control – go take a look and let me know what you think!


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .NET | p&p | Unity
Actions: E-mail | Permalink | Comments (3) | Comment RSSRSS comment feed

Thinking about the future of the Caching block

December 15, 2009 08:36 by Chris

We’re hard at work on Enterprise Library 5.0. One of the things that we’re going to be digging into pretty heavily is .NET 4.0 compatibility. As part of that, I’m beginning to wonder (again) about which blocks still make sense in Entlib.

The Caching block is one of our more popular blocks. It’s been around since before Entlib 1.0 as a stand-alone piece. It was originally intended to suit the needs of occasionally connected client apps to have an offline, persistent cache of information from the server. In practice, it’s been used a lot as a simple in memory cache. We also get constant requests to build a distributed or shared cache.

Requests like this are what got me thinking. In .NET 2.0, the ASP.NET team did a ton of work to make System.Web.Cache work outside of web apps (sadly, they never updated their docs to say so). Since they’re at a lower level than we can write at, the web cache stuff makes a much, much better in memory cache than we can. It monitors overall memory usage, for example, while the best we can do is track how many items are in our cache. With the upcoming release of the cache-formerly-known-as-Velocity, Microsoft has a quality distributed cache technology available. We’d be nuts to try and replicate all that work. We did an analysis of the APIs between our CacheManager and the Velocity cache and came to the conclusion that wrapping Velocity in our interface would cost you a huge amount of capability, so we decided the best guidance was “use Velocity” rather than go through the caching block.

Finally, in .NET 4.0, there’s a new namespace called System.Runtime.Caching, which provides essentially the ASP.NET cache mechanism, but with a provider model behind it. So you can use the existing cache, but you could also plug in new implementations of caching as well.

So, here’s my thinking: given the presence of System.Runtime.Caching, does it make sense to have the caching block at all in Entlib 6? The only scenario that isn’t met by it is the persistent offline cache, and that can be done by building a new cache provider. We’ve always said that p&p’s job was to fill gaps in the platform until the platform catches up. In this case, the platform has definitely caught up, and even passed us in some ways.

Do you use the caching block? Does it do anything you couldn’t do as well or better through the framework provided mechanisms? Is it just backwards compatibility keeping you on it, or is there something I’m missing?

Let us know!


Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: Entlib | p&p | .NET
Actions: E-mail | Permalink | Comments (8) | Comment RSSRSS comment feed

A new article in MSDN (well, kind of…)

November 5, 2009 14:25 by chris

MSDN magazine has just published my latest article. It’s part of the Inside Microsoft patterns & practices online column, and it’s about building libraries that take advantage of dependency injection. I used the work we did rearchitecting Enterprise Library 5 as a sort of case study of the goals, forces, and resolutions. I’m actually quite proud of what we did here, and thought that others might be interested.

Unfortunately, for those of you who get the printed magazine, you may see my name on the cover, but the description of the article is actually from Brian Randell’s article from October’s issue.  I will be having … words … with the magazine staff over this one tomorrow. Sorry Brian, TFS work items are something I’m very happy to let you be the expert in.

Anyway, if you’re interested in how Entlib 5 works under the hood, or want to write a library that uses a DI container without forcing your users to use a specific container, please check it out. And let me know what you think!


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: p&p | Unity | Entlib | .NET
Actions: E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed

Updating the Wiki sample to MVC RC1

February 16, 2009 10:10 by Chris

The recently released ASP.NET MVC Release Candidate broke a couple things in my Wiki sample I originally built for MSDN magazine. So, I've updated them again. Major changes:

  • Updated the ModelBinder implementation to match the new semantics
  • Using the global model binder registration instead of the attributes on the action method (although to be honest there's no really good reason for this)
  • No more view codebehind files

At this point, the sample runs, but it's showing it's pedigree as code that's come up from the original CTP's through beta. So after the final release, I'll do one more refresh on this project, and rebuild it from scratch using the final project templates and the latest MVC stuff. I don't expect a whole lot of change in the controllers, and none in the domain model. But the views I expect will change significantly. Hopefully I can grab one of the new themes from the MVC design gallery so folks don't need to keep looking at my ugly lack of CSS skills. ;-)

I've put a permanent home for this sample on my blog at this page: http://www.tavaresstudios.com/Blog/page/ASPNET-MVC-Wiki-Sample.aspx. Go there for download instructions.

Have fun!


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .NET | Unity | MVC
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Entlib 5 - and we're off!

January 27, 2009 06:17 by Chris

We're officially kicking off the planning for Enterprise Library 5, and we want your input.

Please head over to Grigori's announcement and give us your opinions on what you want to see.

Basically, what we're looking for is this: you have $100 to put into Enterprise Library 5. It can be spent on bug fixes, new features, documentation, labs, whatever you want, but you can't go over. The more you spend, the more important you think that particular thing is. So, how do you want to spend you $100?

Please either post to Grigori's blog, or here.

Thanks!


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .NET | Entlib | p&p
Actions: E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed

Resolving a Singleton? Here's how...

January 23, 2009 18:01 by chris

A user posted a question on the Unity Codeplex forum a couple of days ago. He wanted to configure Unity through the configuration file to resolve a singleton object. My first thought was "of course, that's easy". Then I read the actual question and it got a bit more interesting. I thought I'd put my response here instead of the forum because I thought it was an interesting discussion, and I'd like it to still be around the next time it came up.

The thing was, the object in question was an actual singleton, along these lines:

public class MySingleton : IMySingleton { 
    private MySingleton() { }
    public static MySingleton Instance { 
        get { return instance; } 
    } 
    private static MySingleton instance = new MySingleton(); 
} 

He wanted to configure Unity to, essentially, return the Instance property of this singleton class during resolution. That's not so easy.

So, how do you fit something like this into the container? You could write an extension or custom config node to special case it, but that's just asking for trouble. Plus, it encourages use of singletons, which are pretty well understood to be Not A Good Thing these days.

Unfortunately, many times the singleton behavior is forced upon you by libraries or frameworks. Or you may have lots of other code that isn't using a container that you want to leave unchanged. So what do you do?

Luckily in this case, the singleton has an interface on it. So what I'd do is start by creating a new class that has a public constructor, implements the singleton interface, and defers all the methods to the underlying singleton.

public class MySingletonWrapper : IMySingleton {
    public void MyMethod() {
        return MySingleton.Instance.MyMethod(); 
    }
}

Something along those lines.

Next, I'd configure the container to inject the wrapper when asked to resolve IMySingleton. The nice thing about this is that you get simple integration with the code you currently have, and your new classes which you build up through the container are ignorant of both the singleton class and the wrapper; they just use the interface.

You could stop there. That's the nice thing about proper refactoring: at each step you could stop and still leave your system in a working state. But why? Why not get rid of the singleton and let the container manage the object instances? This is pretty easy through more refactorings.

The first thing to do is change the type of the Instance property on the singleton to return the interface type rather than the concrete type. This should be pretty transparent to the callers, and your compiler will tell you if any edits are required.

The next step is to move the guts of the interface implementation out of the MySingletonClass and into the MySingletonWrapper class. Then change the instance the singleton manages to an instance of MySingletonWrapper instead. Finally, change the methods on the interface to delegate to the wrapper instance instead.

public class MySingletonWrapper : IMySingleton
{
    public void MyMethod() {
        DoStuffHere();
    }
}

public class MySingleton : IMySingleton
{
    public IMySingleton Instance {
        get { return instance; }
    }

    private static IMySingleton instance = new MySingletonWrapper();

    // interface implementation now delegates to instance
    public void MyMethod() {
        instance.MyMethod();
    }
}

At this point, all your code should still be running, through the container or not. You should definately change the name of MySingletonWrapper to something a lot more descriptive at this point. That'll be very easy since the only places that use this class name are your container configuration and the MySingleton class.

From here, the next thing I'd probably do is remove the interface implementation from the MySingleton class. This class now has only one responsibility: managing the lifetime of that inner instance.

Now, as you go forward, you should be able to remove references to the explicit singleton and replace them with objects injected from the container. Over time, you should be able to remove all the reference to MySingleton without affecting your code's behavior at all. When the last reference is gone, you delete the singleton class.

And that's how I'd resolve a singleton.


Currently rated 3.5 by 2 people

  • Currently 3.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .NET | Agile | Unity
Actions: E-mail | Permalink | Comments (3) | Comment RSSRSS comment feed

Elegant Code Cast

January 23, 2009 17:01 by Chris

(Whew, I didn't realize I'd gotten so far of the blogging wagon. Time to hop back on!)

At the last Seattle Code Camp, I ended up talking with David Starr for quite a while. He apparently thought I knew what I was talking about (shh! Don't tell him the truth!) and invited me to be a guest on the Elegant Code Cast. It was a great talk about EntLib, life in p&p, Unity, and all sorts of other stuff.

The episode is available here. Thanks again, guys for the great chat!


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .NET | Entlib | p&p | Silverlight | Unity
Actions: E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed

Announcing Unity 1.2 for Silverlight

December 11, 2008 11:10 by Chris

A little early Christmas present for everyone. ;-)

 

What's in it?

The installer includes the binary, the docs, and a new Silverlight version of our Stoplight quickstart (and no, I didn't port the event broker, anyone want to give it a shot?)

What's different?

Probably the biggest difference is that Microsoft.Practices.Unity.dll for Silverlight is contained in a single assembly. We've merged the previous ObjectBuilder2, Unity, and StaticFactoryExtension into the one DLL. This resulted in a slightly smaller overall package and a lot more convenience when referencing the container, since you don't have to hunt for multiple DLLs when adding references.

One thing that's not included is the XML configuration assembly, Microsoft.Practices.Unity.Configuration.dll. There's a simple reason for that - Silverlight doesn't support System.Configuration. We'll have to come up with a new configuration file story. I'm toying with some XAML based ideas on this front, but it'll be a while.

Also, the recently released interception mechanism (Microsoft.Practices.Unity.Interception.dll) hasn't yet been ported, so that's not included either. We'd like to include it going forward, but it'll take some work to it working and we didn't want to delay the release.

The container basically performs the same in Silverlight as it does on the Desktop CLR. The container API is identical. There is one minor gotcha: due to the difference in security model in Silverlight, you can only resolve public types through the container. The desktop version lets you do public or internal.

How'd we do it?

Luckily, the Silverlight environment really is very close to the Desktop CLR. It was mainly a case of pulling out references to things that Silverlight didn't support. We'd already started down this road with some work done in version 1.2. Replacing calls to methods that didn't exist on Silverlight with ones that did, for example. I did have to tweak a couple of source files (for things we missed) but it didn't affect the overall code any.

In order to do the port, I started by creating an empty Silverlight project. I then imported the Unity source files into it, and then let the compiler tell me what stuff didn't work. Yes, I'm lazy that way.

The vast majority of the code works for both desktop CLR and Silverlight. There were a couple cases where we needed environment-specific code. Looking at the source, you'll see a few files with the .Desktop.cs or .Silverlight.cs extensions. These are how we marked up the code that was specific to one platform or the other. The .Silverlight.cs files are only included in the silverlight project, and the .Desktop ones are specific to the desktop project. For classes that needed to be tweaked, I used partial classes, with the partial parts in a platform-specific file. The various custom exceptions are probably the biggest example of this. On the Desktop CLR, exceptions should have a serialization constructor and be serializable. Silverlight doesn't support this. So each exception class is a partial class. The serialization details are in a .Desktop.cs file. The Silverlight project simply omits those files and we're good.

The unit test suite has also been ported, and uses the same approach. Not every test from the Desktop suite is included, of course. We excluded everything having to do with configuration, for example (which turned out to be rather a lot of tests). Taking advantage of the very nice Silverlight Unit Testing Framework made it pretty easy to reuse our existing VSTS test suite in the Silverlight environment.

What's next?

That's up to you! If you're working on a Silverlight project, please download and let us know what you think! What's important for you? Now's the time, as we're currently prepping for the next version of Enterprise Library and Unity.


Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .NET | Silverlight | Unity
Actions: E-mail | Permalink | Comments (7) | Comment RSSRSS comment feed

Presenting - and a MVC sample update

November 14, 2008 05:24 by Chris

(I really should post this stuff before the actual event.)

Last Thursday, I went down to lovely Olympia Washington to present to the South Sound .NET Users group. I did an intro talk on the ASP.NET MVC framework which seemed to be pretty well received. I wanted to thank the group for having me, I had a great time (aside from the drive down ;-)).

This weekend was Seattle CodeCamp 4. While sitting at dinner watching Jason print up the schedule sheets for Sunday, I noticed (after he'd already printed about 100 copies) that there were empty slots in the schedule. Silly me, I figured I already had a talk and volunteered, and ended up re-presenting the MVC talk.

I used the demo wiki code that I originally wrote for my magazine article. In the process, I updated the code to the lastest ASP.NET MVC beta, and then promptly forgot to post it!

So, for those who are interested, here's the latest version. Actually, I've got two version - one "vanilla" and one that integrates the Unity DI container.

Enjoy!

-Chris

MVCMiniWiki.zip (170.51 kb)

MVCMiniWiki-Unity.zip (172.41 kb)


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .NET
Actions: E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed

Hosting BZR Repositories on IIS

September 16, 2008 16:42 by chris

I posted quite a while ago about using the Bazaar distributed version control system to provide offline capabilities for TFS. I've still been using it that way, but I've found that Bazaar is working quite well for me as a personal, low overhead source control system.

One of the nicer things about Bazaar is the easy hosting and sharing of repositories. All you need for a read-only repository is to put it up on web server. No special configuration required. And yet, every time I tried putting a branch up on this server, it failed.

Turned out that the problem comes down to the bazaar repository format. More specifically, there are filenames in there without file extensions, and IIS just doesn't like that (unless you put in a wildcard mapping which has tons of other issues). I was at a loss, when I remembered that I can just fake it with ASP.NET.

The trick was to give the request an extension. And there's an extension already configured that's perfect here - .ashx, or the ASP.NET HTTP Handler. So what I did was build a hander that takes an url like this:

http://www.tavaresstudios.com/branches.ashx/[Repository Name]/... bzr paths here ...

and feed the resulting files back to the bazaar client. The actual path gets munged a little. I don't need to worry about encoding or anything else, just stream the bytes straight back out to the client.

Here's the code:

using System;
using System.Web;
using System.IO;
using System.Configuration;

/// <summary>
/// A small <see cref="IHttpHandler"/> that returns the contents of the file
/// under given pathdata. Used to serve up files that don't have an extension.
/// </summary>
public class BranchesHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string requestedPath = context.Request.PathInfo;
        string root = GetBranchRoot();

        string resultPath = context.Request.MapPath(root + requestedPath, root, false);
        string rootPath = context.Request.MapPath(".", root, false);

        if (!resultPath.StartsWith(rootPath))
        {
            throw new HttpException(404, "File not found");
        }


        context.Response.ContentType = "application/octet-stream";
        CopyFileToResponse(resultPath, context.Response);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private string GetBranchRoot()
    {
        return ConfigurationManager.AppSettings["BranchRoot"];
    }

    private void CopyFileToResponse(string filePath, HttpResponse response)
    {
        if (!File.Exists(filePath))
        {
            throw new HttpException(404, "File not found");
        }

        response.TransmitFile(filePath);
    }
}

As I build future samples, I'll still make them available as .zip files, but I'm also planning to put the bazaar repository up as well for folks who want to track them.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .NET | Personal
Actions: E-mail | Permalink | Comments (2) | Comment RSSRSS comment feed