问题
I am using the Unity framework as IoC container.
My Config looks some like this:
<unity>
<container>
<register type="Namespace1.IFoo, FooAsm"
mapTo="Namespace2.Bar, BarAsm">
</register>
</conainer>
I would like to register a container to use a factory method. How do i achive it using the app.config?
I am looking for something like this:
<unity>
<container>
<register type="Namespace1.IFoo, FooAsm"
factory="Namespace2.Bar, BarAsm"
method="create">
</register>
</conainer>
</unity>
Any suggestsions?
回答1:
This thread offers a nice response about how to add support of Factory methods for Unity. I fact you have to download this bitbucket source (and change the references to 4.0 framework).
If you now add Generic support for Unity you get a pretty awesome solution that might look like this:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity xmlns="schemas.microsoft.com/practices/2010/unity">
<sectionExtension type="Unity.FactoryConfig.FactoryConfigExtension, Unity.FactoryConfig"/>
<alias alias="Factory" type="Namespace1.GenericFactory`1, asm1"/>
<container>
<register type="Namespace1.ITest, asm1">
<factory type="Factory[[Namespace1.ITest, asm1]]" method="Create" />
</register>
</container>
</unity>
</configuration>
Support of generic Factories for unity framework using xml configuration!
Thanks for all comments :)
回答2:
I don't think there is a built-in way to do this currently. I usually just register the factory itself (Map IMyFactory
-to-> MyFactoryImpl
) then inject the factory into the classes that need it, and have the classes call the factory.
However, I think you can probably make something call a factory straight from Unity by making an extension for Unity. There are a couple mentioned in the answers to this question: How to create objects using a static factory method?
来源:https://stackoverflow.com/questions/9943216/unity-factory-via-xml