Autofac property for instance

I am new to Autofac and I try to set a public property in the class every time it is initialized. Here is the script. I have many classes that inherit from "Entity" that follow this basic format ...

public class Person : Entity
{
     public virtual DataContext ServiceContext { get; set; }
     public string FirstName {get; set;}
     ...
}

These classes are usually created using the LINQ query as follows:

var context = SomeContext(connection);    
var people = context.Query<Person>().Where(item => item.FirstName == "Joe").ToList();

What I'm trying to do is pass the "context" object to the ServiceContext property of the Person class every time I create it. In this example, each Person in the list of people will have this property.

Ideally, I would pass the DataContext through the "Entity" constructor, but the problem is that I do not have access to the Entity or Linq provider, since they belong to a third party. So my question is using Autofac, how do I add a “context” to the “ServiceContext” property for each class that comes from “Entity”? It seems that the OnActivating event is close to what I need, but I cannot get it to work.

+3
source share
2 answers

Autofac allows you to enter properties when a component is activated. There are several ways to do this for your purposes.

-, , DataContext. , .

var builder = new ContainerBuilder();

// You can register an instance...
var context = new DataContext(connectionString);
builder.RegisterInstance(context).As<DataContext>();

// OR you can register construction in a lambda...
builder.Register(c => new DataContext(connectionString)).As<DataContext>();

// OR you can register the type with constructor parameters.
builder.RegisterType<DataContext>()
       .WithParameter(
          new NamedParameter("fileOrServerOrConnection", connectionString));

, , :

builder.RegisterType<Person>().PropertiesAutowired();

Person, , Autofac. DataContext . , , "Entity" ( , Autofac ), "PropertiesAutowired".

, @Chingiz:

builder.RegisterAssemblyTypes(typeof(Person).Assembly)
       .Where(t => t.IsAssignableFrom(typeof(Entity)))
       .PropertiesAutowired();

, Autofac /.

+9

,

public class Person : Entity
{
    public Person(DataContext context)
    {
        ServiceContext = context;
    }
    public virtual DataContext ServiceContext { get; set; }
    public string FirstName { get; set; }
}

builder.Register<DataContext>(c => new DataContext(connectionString)).InstancePerHttpRequest();
builder.RegisterAssemblyTypes(typeof (Person).Assembly)
    .Where(t => t.IsAssignableFrom(typeof (Entity)));
0

Source: https://habr.com/ru/post/1789543/


All Articles