I am trying to return an object of type IDocumentTemplateProvider using a delegate as below:
public static class DocumentTemplateProvider
{
private static Func<IDocumentTemplateProvider> _docTemplateProvider;
public static void SetdocTemplateProvider(Func<IDocumentTemplateProvider> docTemplateProvider)
{
_docTemplateProvider = docTemplateProvider;
}
public static void SetDocTemplateProvider<T>() where T : IDocumentTemplateProvider, new()
{
_docTemplateProvider = () => new T();
}
public static IDocumentTemplateProvider TemplateProvider
{
get { return _docTemplateProvider(); }
}
}
However when I'm calling it using:
private static readonly IDocumentTemplateProvider _template = DocumentTemplateProvider.TemplateProvider;
_template is always null. I'm fairly new to C# Func<> delegates so i can't bloody see what I'm doing wrong. Can someone point me to the right direction?
Thanks
UPDATE: To clear ant confusion i've added the full code where _template is initialized and used as is:
public class DocumentModule : IHttpModule
{
private static readonly IDocumentTemplateProvider _template = DocumentTemplateProvider.TemplateProvider;
public void Init(HttpApplication context)
{
context.BeginRequest += OnBeginRequest;
context.EndRequest += OnEndRequest;
}
public void Init(HttpApplication context)
{
context.BeginRequest += OnBeginRequest;
context.EndRequest += OnEndRequest;
}
private void OnBeginRequest(object sender, EventArgs eventArgs)
{
_template.SetProvider();
}
private void OnEndRequest(object sender, EventArgs e)
{
_template.Finalize();
}
public void Dispose()
{
}
}
It is null because it is has never been set. You have two Void methods that set the _docTemplateProvider variable, so you need to call them first, like the example code below