afx-.o
afx-.o

Reputation: 13

SimpleInjector lazy generic registration

I am working with some old asp.net web form pages and trying to get the DI to work but running into an issue with some objects not being created so am aiming to do a lazy implementation in the code behind.

I have the following registration working in the rest of the website:

container.Register(typeof(IDataFactory<,>), new[] { typeof(SqlAccountFactory).Assembly });

To get the lazy aspect I have tried

container.Register<Lazy<IDataFactory<SqlAccountFactory, int>>>(
            () => new Lazy<IDataFactory<SqlAccountFactory, int>>(
                container.GetInstance<IDataFactory<SqlAccountFactory, int>>));

The outcome of this is that the property does not get populated.

Property in code behind of page (as described above this works when not using Lazy):

[Dependency]
public Lazy<IDataFactory<SqlAccountFactory, int>> ProjectCodesRepository;

For reference I am using the code from the documentation to populate the properties in code behinds marked with attributes and all works well bar the above lazy registration.

Is anybody able to help or spot something silly I have done?

Upvotes: 1

Views: 322

Answers (1)

Steven
Steven

Reputation: 172835

Simple Injector's IPropertySelectionBehavior only works on properties. What you defined however is a public field, not a property. If you change it to the following, it will probably start working:

[Dependency]
public Lazy<IDataFactory<SqlAccountFactory, int>> ProjectCodesRepository { get; set; }

It is wise to mark your DependencyAttribute in such way that it only supports properties, by marking it with an AttributeUsageAttribute as follows:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class DependencyAttribute : Attribute { }

This ensures that the C# compiler will show a compile error in case you put the attribute on a field.

Long story short, it has nothing to do with the dependency being lazy.

Upvotes: 1

Related Questions