Injecting property values without Dependency attribute

Jun 15, 2009 at 11:28 AM

Hi all,

Please take a look at the code bellow. Is it possible to inject values to the properties of the class, without decorating them with the Dependency attribute? The goal of the code bellow is to get 111 to be writen to the console output.

Thanks!

    class Program
   
{
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            container.RegisterInstance("Test1", 111);

            var myClassInstance = container.Resolve<MyClass>();
            Console.WriteLine(myClassInstance.Test1);
        }

        public class MyClass
       
{
            public int Test1 { get; set;}
        }
    }

 

Jun 16, 2009 at 5:21 AM

Add:

    container.RegisterType<MyClass>(new InjectionProperty("Test1", new ResolvedParameter<int>("Test1")));

before the resolve call.

 

Jun 16, 2009 at 9:03 AM

Hi and thanks for helping me out.

However I don't see any RegisterType overload that accepts such parameter. I'm using version 1.1.0.0.

Jun 16, 2009 at 5:44 PM

Ah, ok. My first recommendation would be to update to 1.2.

Failing that, this also works:

container.Configure<InjectedMembers>().ConfigureInjectionFor<MyClass>(new InjectionProperty("Test1", new ResolvedParameter<int>("Test1")));

I think you can see why we added the overloads in version 1.2. :-)

 

Jun 16, 2009 at 6:44 PM

I will upgrade immediately. I downloaded Unity by googling "download microsoft unity". Both Google and Bing return as first result a link to download page of 1.1!

Thanks!