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

Tell me what to work on!

March 27, 2009 06:21 by Chris

We’re about to spin up on development of Entlib 5. As part of that, we want to know what you, yes you want to see in it! Grigori has posted a survey. Apparently, if we did everything it’d take us about 3 years, so we’d like some help from the community to pare it down a little.

Please go take the survey and help me out. And help yourself too, if you’re an entlib user or would like to become one.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: p&p | Entlib
Actions: E-mail | Permalink | Comments (5) | 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

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

Writing Custom Lifetime Managers

July 15, 2008 11:00 by Chris

 

Note: I'm going to be doing a webcast on extending the Unity container on July 24th. I'm going to be doing the preparation here since I also need to work on the general extension docs anyway. Let's hear it for killing three birds with one stone! In any event, I'd love to get feedback on this doc before I do the webcast. Does it flow well? Make sense? Are you able to write custom lifetime managers after reading this? Thanks!

The Unity Dependency Injection Container has many extension points. One of the easiest to take advantage of is creating custom lifetime managers. A lifetime manager controls how instances are reused within the container. By default, the Unity container creates a new instance every time the Resolve method is called. This can be changed by registering a lifetime manager, like so:

container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager());

With this registration any time an instance of Foo is requested, you'll get back the same one as long as the container is alive.

Since you can pass in any instance of a lifetime manager, it's pretty easy to write your own to customize how object instances get reused. Let's take a look at the LifetimeManager class and how it works within Unity.

The LifetimeManager class

To implement a custom lifetime manager, you need to create a class that derives from Microsoft.Practices.Unity.LifetimeManager. The important methods are:

public abstract class LifetimeManager : ILifetimePolicy
{
    public abstract object GetValue();
    public abstract void SetValue(object newValue);
    public abstract void RemoveValue();
}

It's also important to preserve the semantics of the LifetimeManager. In particular:

  • There is one instance of a LifetimeManager per object that is resolved from the container. Don't try to write a lifetime manager that handles multiple objects at once. The base class and the container enforce this requirement at runtime.
  • Thread safety around your GetValue and SetValue call are your job. We'll see an example of this later.

The container uses the lifetime manager in a fairly straightforward way. If the object in question hasn't been created yet, the sequence looks like this:

Sequence diagram - No object exists 

(Why yes, my handwriting does stink, thanks for noticing :-))

Basically, when a resolve call happens, type mapping happens first (not in the diagram), and then the current lifetime manager is looked up (based on the type and name being resolved). The GetValue method is called, and it returns null. At that point the construction of the object happens, and at the end the SetValue method is called to store the created object for next time.

That next time looks like this:

Sequence - object exists

If GetValue returns something other than null, that becomes the return value of the Resolve call and the rest of the build up process is short-circuited.

Example: Implementing a PerThreadLifetimeManager

Let's look at a sample implementation. One thing that can be useful is a per-thread lifetime: each thread that requests a particular type gets its own instance, but multiple requests from the same thread get the same instance.

The first thing you need to do is decide how you're going to save the instance. In this case, we need some kind of thread local storage (TLS). Luckily, the .NET framework has support for TLS built in. All we need to do is create a static field in our class, and add the [ThreadStatic] attribute. Since this is a static, we'll need to store multiple objects in it (one per PerThreadLifetimeManager). A Dictionary will do the trick. I'm using a Guid as a key because they're an easy way to generate a key. Our class starts off like this:

public class PerThreadLifetimeManager : LifetimeManager
{
    [ThreadStatic]
    private static Dictionary<Guid, object> values;
    private Guid key;

    public PerThreadLifetimeManager()
    {
        key = Guid.NewGuid();
    }

...
}

Now we just need to implement the GetValue and SetValue methods. They're very straightfoward:

public override object GetValue()
{
    InitializeValues();
    if (values.ContainsKey(key))
    {
        return values[key];
    }
    return null;
}

public override void SetValue(object newValue)
{
    InitializeValues();
    values[key] = newValue;
}

private void InitializeValues()
{
    if (values == null)
    {
        values = new Dictionary<Guid, object>();
    }
}

(The InitializeValues method is used to guarantee that each thread gets it's copy of the dictionary properly initialized, see MSDN for more details).

What About RemoveValue?

There's one more method that we have to implement: RemoveValue. This is a little embarrassing, but there's no reason to implement this method. Nothing in the Unity pipeline ever calls RemoveValue. It's there for those doing more advanced extensions, but out of the box it does nothing. The sample code with this article implements it as an empty function that does nothing.

Example: CachedLifetimeManager and Multithreading

Ironically, the PerThreadLifetimeManager class doesn't actually deal with multithreading. The use of TLS meant that we could pretty much ignore concurrency issues. However, as I'm sure you can imagine, proper threading is a major concern in most other lifetime managers. As an example, we'll build one that provides access to a value stored in a cache. This could be the ASP.NET cache, the Enterprise Library caching block, or anything else.

(Sidebar: The ASP.NET cache works just fine in non-ASP.NET applications. Don't let the System.Web namespace prevent you from using this great piece of technology!)

To insulate our code from the details of caching, I've defined a simple interface that does the bare minimum we need - get and retrieve items:

public interface IStorage
{
    object GetObject(string key);
    void StoreObject(string key, object value);
}

It's named IStorage rather than ICache because this is useful for more than just caching. I'm sure you can easily imagine an implementation that maps to the ASP.NET cache; see the code sample for this article for a working one.

When dealing with multithreaded access, the initial approach is usually to do something like this:

public override object GetValue()
{
    lock (lockObj)
    {
        return storage.GetObject(key);
    }
}

Unfortunately, this doesn't work. Look again at the sequence diagram above. If the object isn't in storage, we want to return null. But the lock is released as soon as GetValue returns, and now we're still open to race conditions. What we need to do is take a lock, and if the value is not in storage, hold the lock until SetValue completes. This serializes the object creation process so that we're guaranteed not to new up more objects than we need.

So, we need to hold onto the lock after GetValue returns. This will, I admit, feel a little weird at first. The basic idea is that if there's no object in storage, return without releasing the lock, and then release the lock in the corresponding call to SetValue. Of course, you can't use the lock() statement anymore to do this, so we need to drop down to the lower-level Monitor.Enter and Exit calls. The resulting methods look like this:

public override object GetValue()
{
    Monitor.Enter(lockObj);
    object result = storage.GetObject(key);
    if (result != null)
    {
        Monitor.Exit(lockObj);
    }
    return result;
}

public override void SetValue(object newValue)
{
    storage.StoreObject(key, newValue);
    TryExit();
}

private void TryExit()
{
    try
    {
        Monitor.Exit(lockObj);
    }
    catch (SynchronizationLockException)
    {
        // This is ok, just means we don't hold the lock
    }
}

The TryExit helper method is there because there are circumstances (particularly when you're calling container.RegisterInstance) where you'll call SetValue directly without having gone through GetValue first. The TryExit method avoids throwing an exception if we're not actually holding the lock.

Experienced multithreaded programmers reading this are probably a little worried right now. We exit GetValue holding a lock. What happens if an exception happens and SetValue never gets called? Isn't the lock abandoned at this point? The answer is yes, but there's a safety net.

There's a new interface defined in ObjectBuilder2 called IRequiresRecovery:

public interface IRequiresRecovery
{
    void Recover();
}

The Recover method will be called by ObjectBuilder if an exception happens during the build up process. So, to make sure the lock gets released, we just implement IRequiresRecovery on our lifetime manager:

public class CachedLifetimeManager : LifetimeManager, IRequiresRecovery
{
    ...

    #region IRequiresRecovery Members

    public void Recover()
    {
        TryExit();
    }

    #endregion
}

... and we're all set.

Odds and Ends

We've spent a lot of time talking about how lifetime managers handle creation and retrieval of instances. What about the end of an instance's lifetime? There's a pretty simple hook here: implement IDisposable on your lifetime manager class, and when the container is Disposed, the lifetime manager will be too. This is your opportunity to do whatever cleanup you need. Take a look at the code for the ContainerControlledLifetimeManager for an example.

Our final detail has to do with the container's open generic support. As I said above, there should be one lifetime manager instance per instance being managed. What happens when you do:

container.RegisterType<IRepository<>, CustomRepository<>>(new ContainerControlledLifetimeManager());

You've actually got many different instances at this point, one for each generic type argument: CustomRepository<User>, CustomRepository<Account>, CustomRepository<Flamethrower>, etc. This causes havoc with the semantics of the lifetime manager, and will result in all sorts of weird exceptions down the line.

The solution to this is generally transparent, but is useful to know about. When you register a lifetime manager for an open generic type, the lifetime manager instance to pass in isn't actually used. Instead, the container holds on to the type of the lifetime manager. When creating a closed generic type, it uses the container itself to resolve a new instance of that lifetime manager type.

Normally, you don't care. However, if for some reason you need a lifetime manager that takes constructor parameters, be aware that for open generics the container will be used to create the lifetime manager, and will need to be configured accordingly.

Wrap-up

That's it for lifetime managers. A complete copy of the sample code is available for download below. The unit tests make use of the Moq mock object framework; you'll need to download that separately to compile and run the tests.

TavaresStudios.Unity.zip (11.52 kb)


Be the first to rate this post

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

Unity and Silverlight: It can be done!

April 9, 2008 10:33 by Chris

Today was our weekly "slack time" day, where I get to go sit in a conference room and experiment with new technology. Today I did this:



Yep, got Unity running under Silverlight 2.0 beta 1. In the end it took me less than four hours (at least 30 minutes of which was waiting for the SDK to install and the obligatory xaml designer crashes). I made a couple boneheaded mistakes  in the project files, so I'm not going to post sources just yet.

Here's an overview of the porting process:

  • Install 2.0 Beta 1 plugin, SDK, Unit test tools and project templates.
  • Create a new Silverlight project.
  • Create Silverlight libraries for ObjectBuilder and Unity.
  • Copy the source for full OB, Unity, into the new projects. Add the files to the project.
  • Compile, fix errors, compile, fix errors, ... etc. ;-)

 Here's the issues I ran into.

Standard binary serialization is gone. As a result, the SerializationInfo and StreamingContext classes are not available. This is an issue because FxCop insists on the four standard constructors on every custom exception class. In Silverlight, there are now THREE standard constructors, not four. So remove them from all the custom exception classes.

The existing code uses methods like Array.Find and List<T>.RemoveAll. Many of these methods were removed from the Silverlight version. So I replaced them with the equivalent Linq expressions. This actually made some code a lot easier to read, which is nice.

System.Configuration and everything associated with it doesn't exist, which involved removing a bunch of stuff from the unit tests. My fault really, they should have been in a separate fixture to begin with.

The IL generation stuff is actually supported on Silverlight, which pleasantly surpised me. I did have to make one change though. When generating the build plan, we have some code that checks to see if you're in full trust, and chooses where to host the dynamic method based on the trust level. This way, in full trust we can do injection on internal or private classes. In Silverlight, you can't do this, and you can't choose where to host your dynamic methods anyway. The net result is that set of code goes away, and we just accept that you can't inject non-public stuff in Silverlight. Unfortunately, that meant changing a bunch of stuff in the test code, as lots of the tests have private nested classes as test subjects. Had to go through and change them all to public, and it worked.

One really weird thing I ran into is in the StagedStrategyChain class. This class takes an Enum, and uses it to determine how many stages the chain has. To figure out how many stages are present, we called Enum.GetValues(), which returns all the enum constant names. Guess what? This method is gone in Silverlight. I cheated by just looping up from zero to find the highest value defined by the enum; it's grotesque, but it worked.

One thing I'd like to throw in: I really, really appreciate the creation of the Silverlight unit test fixture. It would have taken a LOT longer to figure out if this thing was working without it. And since the SL runner is source compatible with the MSTest stuff, I just copied my existing tests in and they just ran. Very, very cool! 

I'm not going to be posting this code just yet, for a couple of reasons. The first is that the project isn't good enough yet; I really need to reorganize the solution I have right now, for example. The second reason is that this is NOT a supported scenario, and I don't want to give the impression it is. So you'll never see this on the Unity codeplex site, for example. Maybe it could be put on UnityContrib eventually?

Anyway, just wanted to let folks know it's not only possible, it was actually pretty easy!


Be the first to rate this post

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

Unity 1.0 is released!

April 4, 2008 09:43 by Chris

I just finished uploading the release of Unity 1.0 to Codeplex. The bits have also been uploaded to MSDN, but it'll take a while to propagate.

The release includes the Unity MSI, plus two more MSIs with Visual Studio 2005 and 2008 integrated documentation. Rather than bloat the main download with three copies of the docs, we chose to make the separate installers available for those who want them.

We've also split out the source as a separate download, so for those who don't trust MSIs or something, you can still grab the source code.

Enjoy! I'm off to work on version 1.1. :-)

 


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 (2) | Comment RSSRSS comment feed

End of the Deconstruction

February 28, 2008 18:01 by Chris

I'd like to thank everyone for the great reception for my Deconstructing ObjectBuilder series. It's good to know I was filling a gap.

However, I'm currently thinking that I'm not going to post the last segment on using OB to wire up to the event broker. I was editing the text for the post last night, and I realized that it needed serious work to update to OB2. Serious enough to take at least a couple of days. And, quite honestly, I think I've got more important things to write about.

So I think I'm going to call an end to the Deconstructing ObjectBuilder series. And intead start a new one, on Unity, extensibility, and how Unity uses OB2. The EventBroker example I've been using is actually included as one of the Unity quickstarts, so I don't even need to update that code for the container. Wink

I have uploaded all the code from the DeconstructingObjectBuilder series so far. This code even works, unlike some of the blog posts with last minute typos in it. Feel free to play with it. You'll need to download and compile the OB2 sources first. But to be honest, with Unity out there (which has made some significant changes to OB2) I'm not sure how much effort that's worth right now. You can tell me.

Thanks for reading, now on to something (sorta) new!

DeconstructingObjectBuilder.zip (37.93 kb)


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5