Unity - Does InjectionProperty result in null properties?

When I

container.RegisterType<IInterface, MyClass>();

everything works, and all dependent properties are annotated with:

[Dependency]

resolved through the container.

But now I have an int property, which I would also like to resolve through the container. It is not passed in the constructor, but as public property. So I tried this:

container.RegisterType<IInterface, MyClass>(
  new InjectionProperty("PropertyName", 1) 
);

Now this property is being introduced, but all other properties annotated with [Dependency] are null and not allowed. If I use InjectionProperty for one property, now I need to explicitly declare all other properties that have the [Dependency] attribute? Or is there a better way to do this?

Thanks.

+3
source share
3

API (runtime) [Dependency]. . , , [Dependency] .

+1

@najmeddine , .

:

public class Service : IService
{
    [Dependency("Key")]
    public Int32 Value { get; set; }
}

:

IUnityContainer unity = new UnityContainer()
   .RegisterType<IService, Service>()
   .RegisterInstance("Key", 2010)

.

Unity 2.0 ( ), ( ) , :

IUnityContainer child = unity.CreateChildContainer()
    .RegisterInstance("Key", 1900);

child Unity.

: http://msdn.microsoft.com/en-us/library/ff660895(PandP.20).aspx

+6

najmeddine, InjectionProperty [Dependency]... , InjectionMethod, [Dependency].

"Override":

class SomeObject
{
    [Dependency("Value")]
    public string Value { get; set; }

    public void OverrideValue(string value)
    {
        this.Value = value;
    }
}

DI :

container.RegisterInstance<string>("Value", "Default Value");

container.Resolve<SomeObject>();

:

container.RegisterType<SomeObject>("NotDefault", new InjectionMethod("OverrideValue", "Other Value"));

container.Resolve<SomeObject>("NotDefault");

, . ( - , .)

0

Source: https://habr.com/ru/post/1716733/


All Articles