Cutting the Fluff From Service Registration With StructureMap - Revisited

This is just a quick update of an older post of mine. Since StructureMap’s convention API has changed quite a bit, here is the updated version of the code used in the post using the new APIs introduced in StructureMap 2.5.4.

The new code is actually easier. It should look something like this … .

Singleton registration convention
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    public class ServicesAreSingletonsAndProxies : IRegistrationConvention
    {
        #region IRegistrationConvention Members

        public void Process(Type type, Registry registry)
        {
            if (!type.IsConcrete() || !IsService(type) || !Constructor.HasConstructors(type))
            {
                return;
            }

            Type pluginType = FindPluginType(type);

            if (pluginType == null)
            {
                return;
            }

            registry
                .For(pluginType)
                .Singleton()
                .Use(new ConfiguredInstance(type)
                {
                  Interceptor = new DynamicProxyInterceptor(pluginType)
                });
        }

        #endregion

        private static bool IsService(Type type)
        {
            return type.Name.EndsWith("Service");
        }

        private static Type FindPluginType(Type concreteType)
        {
            string interfaceName = "I" + concreteType.Name;

            return concreteType
                .GetInterfaces()
                .Where(t => string.Equals(t.Name, interfaceName, StringComparison.Ordinal))
                .FirstOrDefault();
        }
    }

Comments