DependencyAttribute in abstract class

May 13, 2010 at 5:41 AM

 

public abstract class Base
{
    [Dependency]
    public ISomeInterface PropertyA {get; set;}
}

public SomeClass:Base
{
}

In Unity 2.0 PropertyA doesn't get injected by UnityContainer Resolve or BuildUp... In Unity 1.2 this worked just fine...

May 13, 2010 at 5:54 AM

I'm not getting that behavior,  could you post the code which can repro this?

 

Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.
entlib.support@Avanade.com

May 13, 2010 at 7:59 AM

I found where is problem. If in configuration is set some property, unity doesn't try to resolve other properties. For example,

public abstract class BaseClass : IBase
    {
        [Dependency]
        public ISampleProperty SampleProperty { get; set; }

        [Dependency]
        public ISampleProperty MyProperty { get; set; }

        [Dependency]
        public IUnityContainer Container { get; set; }

        public string Name { get; set; }

        public BaseClass()
        {

        }
    }

 

If config is:

<container name="default">
      <register type="ISampleProperty" mapTo="SampleProperty"/>
      <register type="IBase" mapTo="DerrivedClass" name="someName">
        <property name="Name" value="aaa"/>
      </register>
    </container>

Unity sets Name, but leaves unresolved other properties.

If config is:

<container name="default">
      <register type="ISampleProperty" mapTo="SampleProperty"/>
      <register type="IBase" mapTo="DerrivedClass" name="someName"/>
    </container>
All properties is set correctly. (Of course Name isn't set at all)

This behavior is by design?

May 13, 2010 at 8:28 AM
Edited May 13, 2010 at 8:32 AM

Yes, it is by design.  Configuration overrides the attributes so that you can easily modify dependencies set in the code without recompiling.  Here's a related thread - http://unity.codeplex.com/Thread/View.aspx?ThreadId=42429

 

Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.
entlib.support@Avanade.com

May 13, 2010 at 9:59 AM

It would be nice, if there would be possibility to override only part of the attributes.

When unity is creating object and initializing property:
1. Check if property is defined in config. If yes, initialize according it (for example build dependency, or leave null). If not, continue.
2. Check if property has [Dependency]. If yes, resolve.

Maybe, this new behavior can be turned on by some setting in config... Just idea for future implementations.

Thank You for help and fast response.