I undertook implementation of IoC for data service. I did this:
interface IDataService { } and its implementation (take for example RpcJson):
class JsonRpcDataService : IDataService { } Then we register them in the IoC container. It's all clear for now.
Next, go to the actual implementation. I defined the following data service structure:
- Models - everything is clear
- Collectors are helper classes for getting data
- Handlers - helper classes for data processing (save, for example)
We describe the model interface:
interface IBook { string Autor { get; set; } ... } Collector:
interface IBooksCollector { IEnumerable<IBook> GetItems(); ... } And the handler:
interface IBooksHandler { void Save(IBook book); ... } Well and, respectively, for we realize each of them for JsonRpc. Next, we supplement the IDataService interface:
interface IDataService { IBook CreateBook(); IBooksCollector CreateBooksCollector(); IBooksHandler CreateBooksHandler(); } And we implement these methods in JsonRpcDataService . I made them so that I, at the ViewModel level, should only associate IDataService with RpcJsonDataService, and not all interfaces with their implementations. So that in the end I could do something like this:
var dataService = IoC.Resolve<IDataService>(); // Создаем модель IBook book = dataService.CreateBook(); Instead
IBook book = IoC.Resolve<IBook>(); and somewhere before binding
IBook book = IoC.Register<IBook, Book>(); where Book is an IBook implementation for RpcJson . Since there can be a lot of models, instead of a heap of lines of the form:
IoC.Register<IModel, ModelClass>(); It all comes down to one thing:
IoC.Register<IDataService, RpcJsonDataService>(); Along the way I had questions that I ask you to answer:
- Is this approach correct with creating instances? Or can it make a factory of the form
CreateModel<T>(), into which the interface will be passed as a parameterT, and the factory will already decide what to "give"? - Is it worth making interfaces for models at all, or is it better to describe them right away? I
[JsonProperty(...)]them in order not to clutter up with attributes of the form[JsonProperty(...)], necessary for serialization, because these attributes are needed only for the RpcJson server