philiplaureano / LinFu

A framework that adds mixins, inversion of control, DbC, and other language features to the Common Language Runtime.
http://www.codeproject.com/KB/cs/LinFuPart1.aspx
206 stars 30 forks source link

Adding unnamed services returned for named services. #9

Closed msironi closed 13 years ago

msironi commented 14 years ago

Not sure if this is a but or a feature, but it is a change from how LinFu used to work (I have a unit test that started failing with a trunk pull from yesterday).

With the latest LinFu trunk, services added to a container as unnamed services get returned for service queries for a named service. For example:

var container = new ServiceContainer();
var myService = new MyService();
container.AddService<IMyService>(myService);

Assert.IsNotNull(container.GetService<IMyService>());

Assert.IsNull(container.GetService<IMyService>("frobozz"));

The second Assert used to pass it now asserts as the GetService("frobozz") call is returning the unnamed instance.

I suspect this was introduced by the fix for my earlier problem with factories for generic types (although I haven't debugged LinFu to figure out why this started happening).

EDIT: The second if in FactoryStorage.GetDefaultFactory() is what is doing it. And I was right it's part of the changeset for the fix to my earlier generics bug.

    private IFactory GetDefaultFactory(string serviceName, Type serviceType, IFactory factory)
    {
        var defaultNamedServiceInfo = new ServiceInfo(serviceName, serviceType);
        if (factory == null && base.ContainsFactory(defaultNamedServiceInfo))
            factory = base.GetFactory(defaultNamedServiceInfo);

        var defaultServiceInfo = new ServiceInfo(string.Empty, serviceType);
        if (factory == null && base.ContainsFactory(defaultServiceInfo))
            factory = base.GetFactory(defaultServiceInfo);

        return factory;
    }
philiplaureano commented 13 years ago

Fixed it by changing the method body as follows:

private IFactory GetDefaultFactory(string serviceName, Type serviceType, IFactory factory) { var defaultNamedServiceInfo = new ServiceInfo(serviceName, serviceType); if (factory == null && base.ContainsFactory(defaultNamedServiceInfo)) factory = base.GetFactory(defaultNamedServiceInfo);

        if (serviceType.IsGenericType)
        {
            var defaultServiceInfo = new ServiceInfo(string.Empty, serviceType);
            if (factory == null && base.ContainsFactory(defaultServiceInfo))
                factory = base.GetFactory(defaultServiceInfo);    
        }

        return factory;
    }