title: How to inject dependencies with XmlSerializer and Autofac?
body: <p>I have a class named <code>SomeRule</code> that can be serialized in a XML format. The class uses an <code>ISomeService</code> that I would like to be injected via autofac.</p>
  <pre class="lang-cs prettyprint-override"><code>[Serializable]
  public class SomeRule 
  {
      [XmlAttribute(&quot;Attribute1&quot;)]
      public string Attribute1 {get;set;}
  
      [XmlAttribute(&quot;Attribute2&quot;)]
      public string Attribute2 { get; set; }
      
      private readonly ISomeService m_someService;
      
      private SomeRule() { }
  
      public SomeRule(ISomeService someService)
      {
          m_someService = someService;
      }
      
      public void DoSomething()
      {
          m_someService.DoStuff(Attribute1);
      }
  }
  
  public interface ISomeService {
      
      void DoStuff(string param);
  }
  
  public class SomeServiceImpl : ISomeService
  {
      public void DoStuff(string param) =&gt; //    Do something with the stuff.
  }
  </code></pre>
  <p>Now, my program receives an XML string that I would like to deserialize but also, at the same time, have autofac inject the dependency for me.</p>
  <pre class="lang-cs prettyprint-override"><code>void Main()
  {
      string serializedRule =
          &quot;&lt;?xml version=\&quot;1.0\&quot; encoding=\&quot;utf-16\&quot;?&gt;&quot; + 
          &quot;&lt;SomeRule xmlns:xsi=\&quot;http://www.w3.org/2001/XMLSchema-instance\&quot; &quot; +
              &quot;xmlns:xsd=\&quot;http://www.w3.org/2001/XMLSchema\&quot; &quot; + 
              &quot;Attribute1=\&quot;Huuuuuge\&quot; &quot; +
              &quot;Attribute2=\&quot;Cofveve\&quot; /&gt;&quot;;
          
      XmlSerializer xmlSerializer = new XmlSerializer(typeof(SomeRule));
          
      var stringBuilder = new StringBuilder(serializedRule);
      var newRule = xmlSerializer.Deserialize(
          new StringReader(stringBuilder.ToString())) as SomeRule;
  
      // ISomeService was not injected yet. Is it possible?
  }
  </code></pre>
  <p>I can make this work by calling the autofac container, get the registered implementation of the <code>ISomeService</code> interface and assign it to a public property of the <code>SomeRule</code> instance. I am looking for a better solution, one that would not require the class to have a public property.</p>
  <p>Is there a way to automatically inject dependencies with <code>XmlSerializer</code>?</p>