C # Func <> Problem setting delegate properties
I am trying to return an object of type IDocumentTemplateProvider using a delegate as shown 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 call it using:
private static readonly IDocumentTemplateProvider _template = DocumentTemplateProvider.TemplateProvider;
_template is always null. I'm new to C # Func <> delegates so I can't figure out what I'm doing wrong. Can anyone point me in the right direction?
thank
UPDATE: To clear up the ant confusion, I added the complete code where the _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() { } }
+3
source share
1 answer
This is null because it 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
class Program { private static void Main() { DocumentTemplateProvider.SetDocTemplateProvider<Test>(); //OR DocumentTemplateProvider.SetdocTemplateProvider(() => new Test()); IDocumentTemplateProvider _template = DocumentTemplateProvider.TemplateProvider; Console.ReadLine(); } 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(); } } } } internal interface IDocumentTemplateProvider { } public class Test : IDocumentTemplateProvider { }
+1
source share