Pergunta

I'm using some Autofac modules to initialize config files. E.g.:

public class Config()
{
  public String ConnectionString { get; set; }
}

Regarding XML configuration everything looks like:

 <Autofac defaultAssembly="Autofac">
   <components>
     <component type="Autofac.Configuration.Config, Autofac" instance-scope="single-instance" >
       <properties>
         <property name="ConnectionString" value="Cnstring" />
       </properties>
     </component>
   </components>
 </Autofac>

I'm using this configuration to have Configuration, but in order to make it immutable I use a private setter {get; private set;}. This doesn't works in Autofac, can you please advise how should use private setter initialization?

Foi útil?

Solução

In addition to Peter's answer, if you want to stay with property and property injection, you can add "immutability" manually by code, something like that:

public class Config
{
    private string _connectionString;

    public String ConnectionString
    {
        get
        {
            return _connectionString;
        }
        set
        {
            if (_connectionString != null) throw new ReadOnlyException("_connectionString");
            if (value == null) throw new ArgumentNullException("value");

            _connectionString = value;
        }
    }
}

Outras dicas

As long as the property is read-only, Autofac will not be able to initialize it via property injection. You should use constructor injection instead in this case.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top