Archive for the ‘MS’ Category

MEF and ASP.NET MVC sample

April 23rd, 2009

Just blogged it on the other blog.

Categories: MEF, MS | Top Of Page | No Comments » |

MEF and lifetime

January 30th, 2009

It has been interesting three months working on the lifetime story for MEF. Turned out to be bigger and more complex than any one could anticipate. As I walk you through what has been decided and implemented you may find things too trivial, but actually it was huge as key members in our team wanted something way different. Under this light I really considered the MEF/Lifetime a success as we – the feature crew (Wes and Daniel) – were able to demonstrate clearly the impacts of their proposed changes and how our proposal solved key scenarios.

Here is a summary of the top level decisions:

  • We will continue to support singletons and transients (we renamed them to Shared and NonShared)
  • We will continue to support disposable types (even when IDisposable is not part of the public contract of the service)
  • The container will have the ownership of parts it instantiates (we will not transfer ownership to parts)

You can get the bits from CodePlex, Preview 4 has all the lifetime features implemented and documented.

 

CreationPolicy

We now support three creation policies. They can be specified on the part level – using the CompositionOptionsAttribute – or on the import level, using the ImportAttribute. Both sides need to permissible in order to the dependency be satisfied.

  • Shared: former Singleton. A single instance per lifetime domain (ie, container)
  • NonShared: former Factory. Whenever an export is requested, a new instance is created.
  • Any: defines that the part can function as Shared or NonShared, it would be up to the import side to define. If “Any” is specified on both sides, it will default to Shared.

Container and parts references

The CompositionContainer will not hold references to parts it creates, unless for the following cases:

1. The ComposablePart.RequiresDisposal returns true – which for our default programming will be true only when it wraps an object instance that implements IDisposable

2. The part has one or more imports marked with AllowRecomposition=true. In this case, though, we hold conditional references, which means that while there’s an alive export instance the GC won’t collect the part instance.

3. Shared parts

For all other situations, parts are created, exports gathered and we drop the references leaving everything else to the GC.

One thing to note: if have NonShared disposable parts you might incur in memory bloat. There are two ways to avoid that, described below.

 

Disposing the container

Disposing the container will shutdown parts held (possibly disposing them, and disabling recomposition). Lazy exports wont work anymore. As any disposable type, we haven’t engineered the container to be reusable after being disposed.

 

Scoping containers

You can use container hierarchies in order to create scoped lifetime. For example, a web request is a great candidate to be mapped that way. However, as the container depends on Catalogs you will either have to filter the global catalog – the one that the parent container has access to – or handcraft a new catalog. Using the same catalog on the parent and on the child container won’t make much sense IMHO as then you start to have short lived Singletons.. and this doesn’t feel right to me.

Check the Filtering Catalogs for more information on this.

 

Early release of resources

If you don’t want to use container hierarchies, you can also release an object graph. This is a great solution for scoped operations that you control when it starts and ends.

Just use the method ReleaseExport exposed on the CompositionContainer class. It traverses the parts and its imports releases NonShared parts. It stops in Shared parts as we cannot touch them.

 

Lifetime of parts manually added to the container

When you add an object instance directly to the container you do not transfer its ownership to it – at least not now, we’re discussing and reviewing this behavior. However, adding a part manually will cause composition, so new parts may be created to satisfy your object dependencies. Who own them? The container. MEF is smart enough to shutdown them when you remove that object from the container.

 

Ordering

Due to the fact that we support – to some extend – cycled object graphs, we cannot create a 100% deterministic disposal algorithm. Hence, we do not guarantee disposal ordering and urge you to follow a simple guideline:

“Do not use imports on your dispose method.”

That means, do not use the things your part imported on your implementation of the Dispose method. Why? Because as we do not guarantee ordering, they might have been disposed when you try to use them.

 

Conclusion

It’s been a fun ride. Given the fact that we considered removing support for NonShared, transfer ownership of exports to imports and all sorts of options, I’m absolutely positive that we have made the right choices. I’ve learned that there’s no such thing as the perfect design for complex problems. In that case you have to strive for the right trade-offs and make sure you provide solutions for the key scenarios.

Categories: MEF, MS | Top Of Page | 1 Comment » |

A small excerpt from the IoC Container doc

January 7th, 2009

Twitter followers probably know that I’ve been working on an IoC Container document for my team. It goes over several aspects – including why in my view “DI” is a wrong term and should be banished – from history to features and scenarios. I got permission to release some bits of it in the future. The following however is an excerpt I thought I should share.

Another important aspect of common use of IoC Containers lies on the fact that the components that make up an application play no role in defining or constraining the implementation that can satisfy a dependency. The minimal safety is provided by strongly typed contracts, but it ends there. All binding is left for an external entity – the application host.

Given that the ultimate goal is to reduce coupling and promote reuse, this approach makes a lot of sense as it allows components to be used anywhere, with or without a container.

The component can express what is required or optional using natural OOP idioms. For example, multiple constructors will allow the IoC Container to call the one it can satisfy the most arguments. Also public writable properties are considered optional dependencies for most containers. Note that the container is just playing the role of a user of the class, checking constructor overloads and properties that they can provide values for, absolutely no different from a human interacting with the same class.

By sticking with these natural idioms a class will be naturally decoupled, easy to be reused and easy to be tested. The fact that it also plays well with IoC Containers is a consequence of the decoupling exercise, and should not be misunderstood as the main driver.

Categories: IoC, MS | Top Of Page | 7 Comments » |

Again on internals

December 9th, 2008

Dave (he’s a dev on our team) outlines how some things work here, and how difficult it is to decide in favor of openness by default.

Categories: MS | Top Of Page | 2 Comments » |

On internals

November 13th, 2008

I hate internals and privates and lack of extension points. Really! Many times I’ve wondered ‘what’s wrong with these people that hide all this stuff from me? are they concerned I wouldn’t know how to use it?’

Being on the other side now, and trying to slowly change the culture, I have to say that I understand why MS is so reluctant to make things more open by default. And all comes down to the fact that we don’t make breaking changes.

If we were to open a poll and ask developers what they would prefer: more open and extensible API vs no breaking changes, I’d guess you would go with open/extensible. And later act surprised when a new version of the framework broke your app, forced you to make changes on your code in order to get it compiling, and so on.

That doesn’t mean that openness is forbidden and extension points are evil. Just that we think very – and I mean _very_ – carefully about those. Once we ship it, we can’t remove it. We can’t change it. Ever!

That being said, I think we are going slowly but surely in the direction of open-closed principle and composition over inheritance, at least on my team, and this is enough to make me happy (for now).

Categories: MEF, MS | Top Of Page | 9 Comments » |

MEF/Lifetime: NonShared support

November 10th, 2008

MEF currently support two creation policies: Singleton and Factory. You can think of them as Singleton and Transient or even better: Shared and NonShared. Supporting NonShared is very convenient to users, but comes with costs. So we are considering supporting only Singletons in V1.

In the end, all these control your choice of how state should be shared or not between consumers. If you expose an IEmailSender implementation, whether it should be shared between users or not will depend on how much you care about sharing or not the state – if any – in the service implementation.

It doesn’t mean that you can’t mimic NonShared behavior. It just means that you have to write a bit more code in order to do that.

Say that you have a Foo component, and you want that each “consumer” of Foo to have their own exclusive, non-shared copy of it:

public class MyObject
{
    [Import]
    public FooFactory Factory { get; set; }
    
    private Foo _foo;
    public Foo Foo 
    { 
        get 
        { 
            if (_foo == null) 
            {
                _foo = Factory.CreateFoo();
            } 
            return _foo;
        }
    }

    public void DoWork()
    {
        // Do work with Foo
    }
}

So MyObject cannot simply import Foo. It needs to import something that carries the semantic of creating always a new instance. So it imports a Factory that you created.

Now you probably have a Foo that has dependencies. Fair enough. You can support that using at least two approaches.

In the first scenario, you know before hand the dependencies:

public class Foo
{
    public Foo(Baz baz)
    {
       Baz = baz;
    }

    public Baz Baz { get; set; }

    public Bar Bar { get; set; }
}


public class FooFactory
{
    [Import]
    public Bar Bar { get; set; }

    [Import]
    public Baz Baz { get; set; }

    public Foo CreateFoo()
    {
        var foo = new Foo(Baz);

        foo.Bar = Bar;

        return foo;
    }
}

The second situation you do not know the dependencies:

public class Foo
{
    // Assume Foo has unknown dependencies
}

public class FooFactory
{
    [Import]
    public ICompositionService CompositionService { get; set; }

    public Foo CreateFoo()
    {
        var foo = new Foo();

        CompositionService.SatisfyImports( CompositionServices.CreateAttributedPart(foo));

        return foo;
    }
}

We are really looking for feedback on this one. Do you think that’s reasonable? Would you be angry or frustrated if you had to write this code? And before you ask, we are not considering ripping off the feature because we don’t have anything better do to. :-) It all comes down to the fact that supporting factories lead to situations that we are unable to provide good solutions for.

Categories: MEF, MS | Top Of Page | 13 Comments » |

Framework Design Guidelines video

October 30th, 2008

Awesome to see Kryz showing IoC as a solution for testability. I’d add that this is a side effect, not the fundamental goal. The fundamental goal is loosely coupled design. But even so, when I wrote this article almost 4 years ago I would never expect to see a member of the CLR preaching the same things :-)

See for yourself

One thing I’m particular happy is how he used the IoC term, not DI.

Categories: MS | Top Of Page | 1 Comment » |

Common Service Locator library clarifications

October 2nd, 2008

The goal of the CSL is not to be used in your app directly. I think we – the need came from the community and was backup by Glenn, Chris and BradA – all understand IoC quite well to come up with something that misses the point :-)

However, sometimes you’re working on an IoC unfriendly ground. WebForms, for instance. You need to access an IoC container directly from a page or web control, you cannot get it “injected” somehow. Another example is pure NHibernate. Ayende’s gave me this example a few weeks ago: he needs to access the IoC container from a custom user type. Those are the scenarios that you might leverage the CSL. Period.

Categories: MS, OSS | Top Of Page | 8 Comments » |

What’s like to work at Microsoft (part 1 of n)

September 27th, 2008

It’s like having one or two agreements and a hundred of disagreements towards your ideas and proposals

And this is how it’s intended to be. An idea should not be made into a product due to a personal preference, or dogma. That’s why you have to go over a lot to prove that your idea is (or could be) the best for the product – for the users, for the requirements and for the scenarios.

Is it easy? Hell no. It can be especially frustrating to someone – like me – that came from a really small company where we could agree on an idea/direction in a few hours or, worst case scenario, a couple of days. But it does force you to exercise your human interaction abilities. Not taking disagreements as personal attacks, and all that which is easier said than done.

Last Friday I participated in a spec review meeting for MEF. The feature being discussed is currently on MEF (on codeplex drop) but I never took the chance to see it’s implementation. My boss was proposing a few changes, making clear whom requested them and what were the benefits. There were strong disagreements, but he was able to handle them gracefully. I was so impressed. I’m not saying that he won, that everything is going to be done the way he proposed, just how he was able to handle that discussion.

I kinda remembered the other extreme, at apache avalon, the heated discussions that led people to resign (including me) and to the eventual collapse of the whole project. So much to learn…

Categories: MS | Top Of Page | No Comments » |

Castle and .Net 3.5 SP 1

September 24th, 2008

Here are a few things I should clarify publicly regarding Castle and .Net 3.5 SP 1. First, the facts:

- The SP broke DynamicProxy 2 when creating a proxy for generic interfaces/methods (as Fabian described)
- The code that started to throw an exception is there to deal with a very edge case
- Breaking DynamicProxy breaks everyone that uses it (Rhino Mocks, Castle Windsor, NHibernate and Moq – those are the main ones I can think of now)
- I recently confirmed the problem and changed DynamicProxy code to not use those methods “r5323: Disabled the GetOptional/RequiredCustomModifiers calls so all tests (but one) pass”

So now everyone can continue to use DynamicProxy 2 and live happily. MS is going to make a fix available soon, according to scottha, so that we can re-enable that piece of code.

I don’t know, demographically speaking, the number of people affected by this. I do know and understand that publishing a SP that breaks something that was working make us look bad. That being said, I wish people could spend a day close to CLR team and be a fly on the wall on meetings and hallways discussions. Quality is serious business here.

Nothing is perfect, though, and some things slipped. At some point in time there wasn’t a test case for reflection emit that invoked GetOptional/RequiredCustomModifiers for generic interface/methods. Is that the end of the world? I don’t think so. And I’m sure they have one now.

Now, how could this be prevented? I have a dream.. If some team on CLR decided to run Castle tests cases with SP1, they would have detected that. Mono does aggregate external tests cases repositories to test their platform implementation. MS could do the same for a handful of OSS projects, where license is not a problem. If that’s not possible due to legal issues, the CLR team can streamline the communication with OSS teams and get early feedback. I have a dream… :-)

Categories: Castle, MS | Top Of Page | 7 Comments » |