1

I am using Ninject for IoC.

UPDATE

My repository uses XML Serializer to persist objects.

How do I inject dependencies after deserializing an entity with behavior and state in the same class (POCO) and without using the service locator anti-pattern?

This is the Save method:

public void Save(IIntegrationService service)
{
    if (service.Id == 0)
         servico.Id = GetNewServiceId();

    var serializer = new XmlSerializer(service.GetType());

    using (TextWriter writer = new StreamWriter(File.Open(GetStoreFileName(service), FileMode.Create)))
    {
        serializer.Serialize(writer, service);
    }
}

This is the GetAll method:

public List<IIntegrationService> GetAll()
{
    var services = new List<IIntegrationService>();
    foreach (string fileName in Directory.GetFiles(StoreDirectory, "*.xml"))
    {
        Type serviceTypeOfFile = GetServiceTypeByGUID(GetGUIDFromFileName(fileName));

        var serializer = new XmlSerializer(serviceTypeOfFile);
        using (XmlReader reader = XmlReader.Create(fileName))
        {
            var service = (IIntegrationService) serializer.Deserialize(reader);
            services.Add(service);   
        }

        return services;
    }
}

The problem is that the service creation does not comes from ninject kernel, so, the dependencies are not injected.

Vinicius Gonçalves
  • 2,514
  • 1
  • 29
  • 54
  • 2
    "My repository uses serialization and deserialization to persist objects." - Show us the code. What have you tried? Also, if you are using binary serialization, you are in for a nasty surprise when you upgrade your application and increment the assembly version number because your app won't be able to deserialize the objects in the database anymore. – NightOwl888 Mar 02 '15 at 21:59
  • 3
    The core of your problem is that you try to do dependency injection into entities. Prevent from doing this. Related: https://stackoverflow.com/questions/28715966/entity-framework-object-materialization-and-dependency-injection – Steven Mar 02 '15 at 22:21
  • 1
    @Vinicius please upload the code. or this post might be flagged. I am really interested in what you are trying to do. so please upload it :) – Ian CT Mar 03 '15 at 08:33

1 Answers1

1

You can use the method IKernel.Inject(object, IParameter[]) to inject dependencies into any object that has property injection on it. however, I would echo the comments above and suggest that you refactor your code so that services/behavior is separate from your data objects/entities.

Dave Thieben
  • 5,388
  • 2
  • 28
  • 38