Is there a better way than this to inject a function into an object in Unity?

AlfredBr

I'm a Unity noob, and I have a question. I want to inject an IAgeCalculator into each instance of IPerson so that the IAgeCalculator instance is available to any IPerson that I might later create.

Here is what I have tried so far. It works, but it does not feel right.

static void Main(string[] args) 
{
    IUnityContainer container = new UnityContainer();
    container.RegisterType<IAgeCalculator, AgeInYearsCalculator>("Years");
    container.RegisterType<IAgeCalculator, AgeInDaysCalculator>("Days");

    // Using the initializer like this does not feel right, 
    // but I cant think of another way...

    var ageCalculator = container.Resolve<IAgeCalculator>("Days");
    var personInitializer = new InjectionMethod("Initializer", ageCalculator);
    container.RegisterType<IPerson, Person>(personInitializer);

    var person1 = Factory<IPerson>.Create(container);
    person1.Name = "Jacob";
    person1.Gender = "Male";
    person1.Birthday = new DateTime(1995, 4, 1);

    var person2 = Factory<IPerson>.Create(container);
    person2.Name = "Emily";
    person2.Gender = "Female";
    person2.Birthday = new DateTime(1998, 10, 31);
}

Here are my class definitions:

public interface IAgeCalculator 
{
    string GetAge(IPerson person);
}

internal class AgeInYearsCalculator : IAgeCalculator
{
    public string GetAge(IPerson person) {
        var years = DateTime.Now.Subtract(person.Birthday).TotalDays / 365;
        return years.ToString("0.00") + " years";
    }
}

internal class AgeInDaysCalculator : IAgeCalculator 
{
    public string GetAge(IPerson person) {
        var days = (DateTime.Now.Date - person.Birthday).TotalDays;
        return days.ToString("#,#") + " days";
    }
}

public interface IPerson
{
    string Name { get; set; }
    string Gender { get; set; }
    DateTime Birthday { get; set; }
    string Age { get; }
}

public class Person : IPerson
{
    private IAgeCalculator _ageCalculator;
    public void Initializer(IAgeCalculator ageCalculator) {
        _ageCalculator = ageCalculator;
    }

    public string Name { get; set; }
    public string Gender { get; set; }
    public DateTime Birthday { get; set; }
    public string Age => _ageCalculator.GetAge(this);
}

public class Factory<T> 
{
    public static T Create(IUnityContainer container) {
        return container.Resolve<T>();
    }
}

Is there a better way?

AlfredBr

Register IAgeCalculator using RegisterInstance<T> (not RegisterType<T>) and pass in an instance derived from that type.

static void Main(string[] args)
{
    IUnityContainer container = new UnityContainer();
    container.RegisterInstance<IAgeCalculator>("Years", new AgeInYearsCalculator());
    container.RegisterInstance<IAgeCalculator>("Days", new AgeInDaysCalculator());
    container.RegisterType<IPerson, Person>();

    var person1 = Factory<IPerson>.Create(container);
    person1.Name = "Jacob";
    person1.Gender = "Male";
    person1.Birthday = new DateTime(1995, 4, 1);

    var person2 = Factory<IPerson>.Create(container);
    person2.Name = "Emily";
    person2.Gender = "Female";
    person2.Birthday = new DateTime(1998, 10, 31);
}

Then in your Person class, mark AgeCalculator with the [Dependency] attribute.

public class Person : IPerson
{
    [Dependency("Days")]
    public IAgeCalculator AgeCalculator { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public DateTime Birthday { get; set; }
    public string Age => AgeCalculator.GetAge(this);
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Inject javascript into object function

分類Dev

Is there a better way to do this than echo?

分類Dev

Better way to override a function definition

分類Dev

AngularJS: Is there a better way to achieve this than the one specified?

分類Dev

Is there a better way to achieve this result than using sscanf?

分類Dev

Is there a better way to run this function on two separate elements?

分類Dev

Is there a better way to horizontally align elements, than text-align: centre?

分類Dev

A better way to add text to ca cv::Mat than cv::putText()?

分類Dev

Is there a better way to implement a functional recursive findById in javascript than this?

分類Dev

What is better way for merge sort? recursive function or non-recursive?

分類Dev

Is there a Better way to handle Same callback function but different input params?

分類Dev

Is it better to handle object creation inside the function or add it to the parameter list

分類Dev

Multilayered-LIST-to-ARRAY-transformation in R and any better way than using loops

分類Dev

Is there a better way to do modulo in a finite field when directly working on polynomials rather than binary numbers?

分類Dev

Is there a better way to model this access pattern than to use two global secondary indexes (GSI)?

分類Dev

Is there any way to add an object other than CString to a CComboBox in MFC?

分類Dev

Tensorflow tf.nn.softmax() function performs much better than hand-written softmax

分類Dev

DRY way to assign function values to an object

分類Dev

Is there a better way of comparing dates

分類Dev

A better way to detect the cursor?

分類Dev

Better way to return boolean

分類Dev

A better way to introspect a capture

分類Dev

Is there a better way to do this? BASH

分類Dev

better way to do this in MATLAB?

分類Dev

Is there a better way to loop code?

分類Dev

Which is the better way of using Hibernate seesion.delete() - Delete by Id or delete by object?

分類Dev

A better way to deep update an object in ES6 with lodash or any other library

分類Dev

How to avoid jquery initialize object as function more than once

分類Dev

PlayFramework how to inject object to a template

Related 関連記事

  1. 1

    Inject javascript into object function

  2. 2

    Is there a better way to do this than echo?

  3. 3

    Better way to override a function definition

  4. 4

    AngularJS: Is there a better way to achieve this than the one specified?

  5. 5

    Is there a better way to achieve this result than using sscanf?

  6. 6

    Is there a better way to run this function on two separate elements?

  7. 7

    Is there a better way to horizontally align elements, than text-align: centre?

  8. 8

    A better way to add text to ca cv::Mat than cv::putText()?

  9. 9

    Is there a better way to implement a functional recursive findById in javascript than this?

  10. 10

    What is better way for merge sort? recursive function or non-recursive?

  11. 11

    Is there a Better way to handle Same callback function but different input params?

  12. 12

    Is it better to handle object creation inside the function or add it to the parameter list

  13. 13

    Multilayered-LIST-to-ARRAY-transformation in R and any better way than using loops

  14. 14

    Is there a better way to do modulo in a finite field when directly working on polynomials rather than binary numbers?

  15. 15

    Is there a better way to model this access pattern than to use two global secondary indexes (GSI)?

  16. 16

    Is there any way to add an object other than CString to a CComboBox in MFC?

  17. 17

    Tensorflow tf.nn.softmax() function performs much better than hand-written softmax

  18. 18

    DRY way to assign function values to an object

  19. 19

    Is there a better way of comparing dates

  20. 20

    A better way to detect the cursor?

  21. 21

    Better way to return boolean

  22. 22

    A better way to introspect a capture

  23. 23

    Is there a better way to do this? BASH

  24. 24

    better way to do this in MATLAB?

  25. 25

    Is there a better way to loop code?

  26. 26

    Which is the better way of using Hibernate seesion.delete() - Delete by Id or delete by object?

  27. 27

    A better way to deep update an object in ES6 with lodash or any other library

  28. 28

    How to avoid jquery initialize object as function more than once

  29. 29

    PlayFramework how to inject object to a template

ホットタグ

アーカイブ