Silverlight and Registering lazy

Jun 11, 2014 at 9:27 AM
Hello,
I premit that I'm new to SimpleInjector, I've used in past FunQ and Caliburn Micro's IoC .... I wish to register an object of type FilterResponse filling it via Func<>

I expected it to be called the first time I try to resolve it and not immediatly

My registration code is
  var container = new Container();

            container.RegisterSingle<IBodInquiryRepository>(new BodInquiryRepository());

            container.RegisterSingle<FilterResponse>(()=> 
                
                {
                   // var repo = container.GetInstance<IBodInquiryRepository>();

                   // var filterResponse = repo.GetFiltersForInquiries(1234);
                    var filterResponse = new FilterResponse();

                    return filterResponse;
                });
In my real app I will call the repo

Thanks
Coordinator
Jun 11, 2014 at 10:07 AM
Edited Jun 11, 2014 at 10:07 AM
Does your configuration contain a call to container.Verify? A call to verify will iterate all root objects and forces them to be created. The registration of a Func<T> factory itself will not cause Simple Injector to execute it. It is done lazily.

Your configuration however troubles me, because now composition of the object graph is depending on the database (assuming that the BodInquiryRepository calls the database). This makes your configuration more fragile and harder to test.

I would therefore suggest moving the call to GetFiltersForInquiries out of the object composition and delay calls to it. You can do this for instance by letting application code depend on IBodInquiryRepository and call its GetFiltersForInquiries method, or you can register a factory that contains a GetFilterResponse() method:
public interface IFilterResponseProvider
{
    FilterResponse GetFilterResponse();
}

public class FilterResponseProvider : IFilterResponseProvider
{
    private readonly Lazy<FilterResponse> response;
    public FilterResponseProvider(IBodInquiryRepository repository) {
        this.response = new Lazy<FilterResponse>(() => repository.GetFiltersForInquiries(1234));
    }

    public FilterResponse GetFilterResponse() {
        return this.response.Value;
    }
}

container.RegisterSingle<IFilterResponseProvider, FilterResponseProvider>();
Now you can let consumers depend on this new IFilterResponseProvider and let them call the GetFilterResponse() method.
Jun 11, 2014 at 11:40 AM
Hello.
yes I had a Verify in the end, ASAP I'll be back to the office I'll give a try!
Thanks
Coordinator
Jun 11, 2014 at 11:51 AM
If you're thinking about removing the call to Verify, please read this first.