views:

161

answers:

1

I wold like the unity framework to resolve a static class "MyStaticObject" specified in my config file. As my class is static, I am getting an error "The type StaticObject does not have an accessible constructor."

My config file looks as below:

  <unity>
    <typeAliases>
      <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
      <typeAlias alias="StaticObject" type="MyStaticAssembly.MyStaticObject, MyStaticAssembly, Version=1.0.0.0" />
      <typeAlias alias="staticobject" type="MyStaticAssembly.MyStaticObject, MyStaticAssembly" />
    </typeAliases>

    <containers>
      <container> 
        <types>
          <type type="StaticObject" mapTo="staticobject" name="My Static Object">
            <lifetime type="singleton"/>
          </type>
        </types>
      </container>
    </containers>
  </unity>

I would highly appreciate any help.

+2  A: 

Unity (or any IoC container framework) is basically a super-factory, creating objects and handing them to you. How is it supposed to create an instance of a static class?

Refactor your design to use a non-static class. If necessary create a class that wraps the static class and delegates to it.

EDIT: If you specifically want the container to call an existing static factory method, you can use StaticFactoryExtension.

EDIT: Unless you need to swap out implementations after deployment, I'd recommend avoiding XML configuration and writing fluent configuration code (calling container.RegisterType, etc.) in a single place in your application instead. You can still use separate configuration code in your unit tests.

TrueWill