I have one interface with 2 classes implementing it, I need to load each class but unity has:
m_unityContainer.Resolve() // Where is the interface IGeneric
my config looks like:
<type type="IGeneric" mapTo="ClassA">
</type>
<type type="IGeneric" mapTo="ClassB">
</type>
any ideas?
thanks
You could also use a generic interface as follow:
public interface IGeneric{}
public interface IGeneric<T> : IGeneric{}
Then have a type safe resolution of the the interface:
container.RegisterType<IGeneric<ClassA>, ClassA>();
container.RegisterType<IGeneric<ClassB>, ClassB>();
ClassA classA = container.Resolve<IGeneric<ClassA>>();
ClassB classB = container.Resolve<IGeneric<ClassB>>();
Some interesting things start happening when you go down this road...
This will give you all the registered classes that implement IGeneric.
IEnumerable<IGeneric> objects = container.ResolveAll<IGeneric>();
I found out the solution, a name property has to be used in each entry:
and the code will look like
obj= container.ResolveAll("ClassA");
Schalk - looks good. What would be the notation for specifying that in the Unity.config?
Here is a slightly different way. I am using Unity.2.1.505.2 (just in case that makes a difference).
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity>
<container>
<register type="IVehicle" mapTo="Car" name="myCarKey" />
<register type="IVehicle" mapTo="Truck" name="myTruckKey" />
</container>
</unity>
Here is the DotNet code.
UnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Configure(container);
IVehicle v1 = container.Resolve<IVehicle>("myCarKey");
IVehicle v2 = container.Resolve<IVehicle>("myTruckKey");
See:
http://msdn.microsoft.com/en-us/library/ff664762(v=pandp.50).aspx
Related
I hope that you're all coding well. So... I was refactoring the client side of the GWT app I work on and I was wondering about something. Looking after an answer days after days, I decided to ask you for your point of view...
The title is quite understanding, but, there is a snippet of what I'd like to do.
I'd like to change stuff like this
public AnnotatedObject annotated = GWT.create(AnnotatedObject.class);
by something like this
#CreativeAnnotation
public AnnotatedObject;
I had to say that in my xxx.gwt.xml, I have done something like this :
<replace-with class="package.AnnotationObject2">
<when-type-is class="package.AnnotationObject" />
</replace-with>
As you can see, my deffered replacement class is AnnotationObject2, and for the moment, I add a line between the ones above and I have :
<replace-with class="package.AnnotationObject1">
<when-type-is class="package.AnnotationObject" />
<when-property-is name="type" value="object1" />
</replace-with>
<replace-with class="package.AnnotationObject2">
<when-type-is class="package.AnnotationObject" />
<when-property-is name="type" value="object2" />
</replace-with>
I don't really like to play with metadata of my xxx.html, so the result I'd like is this one :
#CreativeAnnotation(type = "object2")
public AnnotatedObject;
So, do you think that sort of thing is possible with GWT (I have to say that I work with GWT 2.5, 'cause of my client desires) ? If yes, may you help me ?
Thanks in advance.
EDIT : I mean, I know about GIN... Just wondering how to do it from scratch.
You can achieve this by using dependency injection with GIN.
GIN automatically use GWT.create() to create an object that has to be injected.
Ex:
class MyView {
interface MyUiBinder extends UiBinder<Widget, MyView> {
}
#Inject
MyView(MyUiBinder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
}
}
And with dependency injection, you also specify which implementation of your interface to instantiate in your GIN module:
public class MyModule extends AbstractGinModule {
protected void configure() {
bind(AnnotationObject.class).annotatedWith(Names.named("object1").to(AnnotationObject1.class);
bind(AnnotationObject.class).annotatedWith(Names.named("object2").to(AnnotationObject2.class);
}
}
And then in your code:
public class MyClass {
#Inject
public MyClass(#Named("object1") AnnotationObject annotationObject) {
...
}
}
You can also use custom binding annotation instead of the Named annotation.
You can write your own generator if you don't want to use GIN - for something like this it would be pretty trivial.
I'm confuse about IAdaptable and related classes. Which class is the adapter, the adaptee, the adaptable type?
[Context]
I have a context menu for entries of a table/tree viewer. Certain actions in the context menu must not be visible depending on the state of the respective object in the viewer (i.e. attribute value of a row in the table viewer).
I can achieve this with a config like this in plugin.xml:
<extension
point="org.eclipse.ui.popupMenus">
<objectContribution
adaptable="false"
id="<some_id>"
objectClass="<object_class_of_viewer_entry>">
<visibility>
<objectState name="buildable" value="true"/>
</visibility>
<action
class="<my_action_class>"
However, this only works if the object class implements org.eclipse.ui.IActionFilter.
[Problem]
My object class can't implement IActionFilter, I don't want to change its interface. Hence, I need to work around that using the IAdaptable mechanism.
Reading the Eclipse documentation left me all puzzled with terms (adapter, the adaptee, adaptable type) and I'm still confused about how to go about my problem.
The object class (referred to by in the above config) must remain untouched.
My approach was the following.
<extension
point="org.eclipse.core.runtime.adapters">
<factory
adaptableType="<object_class_of_viewer_entry>"
class="MyFactory">
<adapter
type="org.eclipse.ui.IActionFilter">
</adapter>
</factory>
</extension>
MyFactory is like this:
public class MyFactory implements IAdapterFactory {
private static final Class[] types = {
<object_class_of_viewer_entry>.class,
};
#Override
public Object getAdapter(Object adaptableObject, Class adapterType) {
return new <class_that_implements_IActionFilter>((<object_class_of_viewer_entry>) adaptableObject);
}
#Override
public Class[] getAdapterList() {
return types;
}
}
What's wrong about this? Where did I miss something?
Turns out everything, well, almost everything, was correct. I had simply mixed up interface and implementation of object_class_of_viewer_entry in the plugin.xml.
Two articles that helped: http://www.eclipsezone.com/articles/what-is-iadaptable/ and http://wiki.eclipse.org/FAQ_How_do_I_use_IAdaptable_and_IAdapterFactory%3F
I have been trying to use the configurable provider model for handling my MEF imports and exports from MEF Contrib (link). I've read the Codeplex documentation and Code Junkie's blog post (link); however, I can't seem to get the container to create the parts. Where am I going wrong?
Program.cs
namespace MEFTest
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Run();
}
// [ImportMany("command", typeof(IHelp))]
public IEnumerable<IHelp> Commands { get; set; }
void Run()
{
Compose();
foreach(IHelp cmd in Commands)
{
Console.WriteLine(cmd.HelpText);
}
Console.ReadKey();
}
void Compose()
{
var provider = new ConfigurableDefinitionProvider("mef.configuration");
var catalog = new DefinitionProviderPartCatalog<ConfigurableDefinitionProvider>(provider);
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
}
TestCommand.cs
namespace MEFTest
{
//[Export("command", typeof(IHelp))]
public class TestCommand : IHelp
{
private string _helpText = "This is a test.";
public string CommandName
{
get { return "Test"; }
}
public string HelpText
{
get { return _helpText; }
}
}
}
App.Config section:
<mef.configuration>
<parts>
<part type="MEFTest.TestCommand, MEFTest">
<exports>
<export contract="IHelp" />
</exports>
</part>
<part type="MEFTest.Program, MEFTest">
<imports>
<import member="Commands" contract="IHelp" />
</imports>
</part>
</parts>
</mef.configuration>
I don't get any build errors and it runs fine if I switch to the typical attribute-based system that is part of the MEF core (with the appropriate catalog too). Program.Commands is always NULL in the above example. I tried to just use a singular property instead of a collection and get the same results.
When I debug I can get the provider.Parts collection so I know it's accessing the configuration information correctly; however, I get an InvalidOperationException whenever I debug and try to drill into catalog.Parts.
Anyone have any experience as to where I'm going wrong here?
As documented here, you also need this in your config file:
<configSections>
<section
name="mef.configuration"
type="MefContrib.Models.Provider.Definitions.Configurable.PartCatalogConfigurationSection, MefContrib.Models.Provider" />
</configSections>
If you already have that, then it might be interesting to show us the stack trace of the InvalidOperationException that you get when accessing provider.Parts.
I had the same problems and could not get it to work, but here are some details:
It seems that ComposeParts() does not work as expected (at least in the version I used) because it uses static methods, based on Reflection to find all required Imports (so it seems that this part cannot be changed from outside of MEF). Unfortunately we want to use xml configuration and not the MEF attributes.
It works if you add [Import] attributes to the members of the class you you use with ComposeParts(). In your case this would be "Programm". In this case all exports defined in the configuration file will be found.
I could not find any documentation or examples on the MEF Contrib page relating to that problem. Also there is no unittest in the MEF contrib projekt that uses ComposeParts().
A workaround would be to use container.GetExportedValues() to retrieve the values, but in this case you have to set the classes members manually.
Hope that helps.
Suppose I have two types, TypeA and TypeB, that I want to register with Unity. TypeB depends on TypeA so I want to inject TypeA into type B through constructor injection. So I would like to write something like the following and have Unity be smart enough to cascade the resolution for me:
_container.RegisterType<ITypeA, TypeA>();
_container.RegisterType<ITypeB, TypeB>();
How can I tell Unity to resolve TypeA and inject into TypeB?
It looks like this is possible if using a config file, but I don't know how you would do it programmaticaly:
<type name="typeB" type="ITypeB" mapTo="TypeB">
<lifetime type="Singleton"/>
<typeConfig extensionType="...">
<constructor>
<param name="typeA" parameterType="ITypeA">
<dependency/>
</param>
</constructor>
</typeConfig>
</type>
Thanks in advance for any suggestions!
EDIT: So, Unity does handle this for me. However, I think my issue is that I have a class with two constructors:
public TypeB(TypeA typeA)
{
_x = typeA;
}
public TypeB() : this(Something.Value)
{
}
It seems that Unity is having trouble knowing which constructor to use. The first constructor is for unit testing and the second should be used at during runtime. Unity is having trouble with this.
You do it like this:
class TypeA
{
}
class TypeB
{
[InjectionConstructor]
public TypeB([Dependency] TypeA typeOfA)
{
}
}
I wanted to deserialize an XML message containing an element that can be marked nil="true" into a class with a property of type int?. The only way I could get it to work was to write my own NullableInt type which implements IXmlSerializable. Is there a better way to do it?
I wrote up the full problem and the way I solved it on my blog.
I think you need to prefix the nil="true" with a namespace in order for XmlSerializer to deserialise to null.
MSDN on xsi:nil
<?xml version="1.0" encoding="UTF-8"?>
<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="array">
<entity>
<id xsi:type="integer">1</id>
<name>Foo</name>
<parent-id xsi:type="integer" xsi:nil="true"/>
My fix is to pre-process the nodes, fixing any "nil" attributes:
public static void FixNilAttributeName(this XmlNode #this)
{
XmlAttribute nilAttribute = #this.Attributes["nil"];
if (nilAttribute == null)
{
return;
}
XmlAttribute newNil = #this.OwnerDocument.CreateAttribute("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance");
newNil.Value = nilAttribute.Value;
#this.Attributes.Remove(nilAttribute);
#this.Attributes.Append(newNil);
}
I couple this with a recursive search for child nodes, so that for any given XmlNode (or XmlDocument), I can issue a single call before deserialization. If you want to keep the original in-memory structure unmodified, work with a Clone() of the XmlNode.
The exceptionally lazy way to do it. It's fragile for a number of reasons but my XML is simple enough to warrant such a quick and dirty fix.
xmlStr = Regex.Replace(xmlStr, "nil=\"true\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"");