开发者

How can a static class be resolved by the Unity Framework?

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" t开发者_StackOverflow中文版ype="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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜