Skip to content

Custom Objects and Dependency Injection

linvi edited this page Jun 9, 2015 · 3 revisions

Overview

Tweetinvi is using Dependency Injection, Inversion of Control and aggregation instead of inheritance. We use these tools to try to respect the SOLID principles.

But beyond this it means that any developer can easily access any tool available in the library by a simple call to TweetinviContainer.Resolve<T>().

The dependency injection also allows developers to configure which type of concrete object they want to see returned from Tweetinvi methods.

Make Tweetinvi use your objects

First of all I would like to warn all developers that in order to return custom classes of objects, you should be familiar with Tweetinvi and how the library works. Having read the source code is greatly advised. This is specially true if you decide to change DTO (Data Transfer Objects) classes as they are annotated with attributes to simplify the deserialization.

Second advice is that instead of using your own classes, you should inherit from an existing class in Tweetinvi and ask Tweetinvi to use this one.

// Create a class that implement the interface that you want to override
public class MyTweet : Tweetinvi.Logic.Tweet : ITweet
{
    public MyTweet(ITweetDTO tweetDTO, ITweetController tweetController, ITweetFactory tweetFactory, IUserFactory userFactory, ITaskFactory taskFactory, IFactory<IMedia> mediaFactory) 
: base(tweetDTO, tweetController, tweetFactory, userFactory, taskFactory, mediaFactory)
    {
    }
}

// Override Tweetinvi default class
// This code should be invoked before any other code of Tweetinvi
TweetinviContainer.BeforeRegistrationComplete += (sender, args) =>
{
    var container = args.TweetinviContainer;

    // Every method that return ITweet will now return a MyTweet
    container.RegisterType<ITweet, MyTweet>();
};

IMPORTANT NOTE : The TweetinviContainer.BeforeRegistrationComplete should be defined before invoking any code from the Tweetinvi library.

Use any class from Tweetinvi

The TweetinviContainer allows you to reuse any of the class available in Tweetinvi very easily. For example, lets consider you'd like to check if a Tweet respect all the rules in order to be published.

This feature is not publicly available and is performed by Tweetinvi behind the scenes.

var tweet = Tweet.CreateTweet("plop");
var tweetQueryValidator = TweetinviContainer.Resolve<ITweetQueryValidator>();
var canBePublished = tweetQueryValidator.CanTweetDTOBePublished(tweet.TweetDTO);

Obviously this is a very simple example, but it shows that any class can be reused. So feel free to look within the source code and reuse any class that you think will help you.

Clone this wiki locally