1

I am using Microsoft DI with Sitecore 8.2 Update 3. I have registered my Glass Items like this:

serviceCollection.AddTransient<ISitecoreContext>(provider => new SitecoreContext());
serviceCollection.AddTransient<IGlassHtml>(provider => new GlassHtml(serviceProvider.GetService<ISitecoreContext>()));
serviceCollection.AddTransient<ICustomSitecoreContext>(provider => new CustomSitecoreContext(serviceProvider.GetService<IGlassHtml>()));
serviceCollection.AddScoped<ISitecoreService>(provider => new SitecoreService(Sitecore.Context.Database));

Most of these things are resolving. But, when I use the CustomSitecoreContext, the parameter GlassHTML is null. I can see on showservicesconfig.aspx that IGlassHtml is registered. Im thinking its maybe not registered in time to use it this way?

1 Answer 1

3

Not knowing the details of your implementation on ICustomSitecoreContext, it looks to me like you are registering the dependencies incorrectly. While the ISitecoreContext needs the factory method to instantiate a new SitecoreContext - your other dependencies should be able to be created by the container.

E.g:

serviceCollection.AddTransient<ISitecoreContext>(provider => new SitecoreContext());
serviceCollection.AddTransient<IGlassHtml, GlassHtml>();
serviceCollection.AddTransient<ICustomSitecoreContext, CustomSitecoreContext>();
serviceCollection.AddScoped<ISitecoreService>(provider => new SitecoreService(Sitecore.Context.Database));

If you register them like that, your container then takes care of making sure that the IGlassHtml object injected into your CustomSitecoreContext class is instantiated.

Alternatively - if you need to use the factory method, then you need to use the provider method from the lambda. Like this:

serviceCollection.AddTransient<IGlassHtml>(provider => new GlassHtml(provider.GetService<ISitecoreContext>()));
serviceCollection.AddTransient<ICustomSitecoreContext>(provider => new CustomSitecoreContext(provider.GetService<IGlassHtml>()));

Hope that helps!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.