Code Monkey home page Code Monkey logo

di's Introduction

DI

Dependency injection framework for go programs (golang).

DI handles the life cycle of the objects in your application. It creates them when they are needed, resolves their dependencies and closes them properly when they are no longer used.

If you do not know if DI could help improving your application, learn more about dependency injection and dependency injection containers:

There is also an Examples section at the end of the documentation.

DI is focused on performance. It does not rely on reflection.

Table of contents

Build Status go.dev reference Coverage Status Maintainability codebeat goreport

Basic usage

Object definition

A Definition contains at least the Name of the object and a Build function to create the object.

di.Def{
    Name: "my-object",
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
}

The definition can be added to a Builder with the Add method:

builder, _ := di.NewBuilder()

builder.Add(di.Def{
    Name: "my-object",
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
})

If you have an already built object to put in the container, you can use the Set shortcut:

obj := &MyObject{}

builder, _ := di.NewBuilder()
builder.Set("my-object", obj)

Note that you can override a definition by adding a definition with the same name. This could be useful in some contexts (for example in unit tests to mock a dependency):

builder.Set("my-object", "A")

// override the previous definition
builder.Add(di.Def{
    Name: "my-object",
    Build: func(ctn di.Container) (interface{}, error) {
        return "B", nil
    },
})

// override the definition again, as if the two previous ones never existed
builder.Set("my-object", "C")

Object retrieval

Once the definitions have been added to a Builder, the Builder can generate a Container. This Container will provide the objects defined in the Builder.

ctn := builder.Build() // create the container
obj := ctn.Get("my-object").(*MyObject) // retrieve the object

The Get method returns an interface{}. You need to cast the interface before using the object.

Definitions and dependencies

The Build function can also use the Get method of the Container. That allows to build objects that depend on other objects defined in the Container.

di.Def{
    Name: "object-with-dependency",
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObjectWithDependency{
            Object: ctn.Get("my-object").(*MyObject),
        }, nil
    },
}

You can not create a cycle in the definitions (A needs B and B needs A). If that happens, an error will be returned at the time of the creation of the object.

Unshared objects

By default, the Get method called on the same container always returns the same object. The object is created when the Get method is called for the first time. It is then stored inside the container and the same instance is returned in the next calls. That means that the Build function is only called once.

If you want to retrieve a new instance of the object each time the Get method is called, you need to set the Unshared field of the definition to true.

builder.Add(di.Def{
    Name: "my-object",
    Unshared: true, // The Build function will be called each time.
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
})

ctn.Get("my-object").(*MyObject) == ctn.Get("my-object").(*MyObject) // false

Scopes

The principle

Definitions can also have a scope. They can be useful in request based applications, like a web application.

di.Def{
    Name: "my-object",
    Scope: di.Request,
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
}

The available scopes are defined when the Builder is created:

builder, err := di.NewBuilder(di.App, di.Request)

Scopes are defined from the more generic to the more specific (eg: App โ‰ป Request โ‰ป SubRequest). If no scope is given to NewBuilder, the Builder is created with the three default scopes: di.App, di.Request and di.SubRequest. These scopes should be enough almost all the time.

The containers belong to one of these scopes. A container may have a parent in a more generic scope and children in a more specific scope. The Builder generates a Container in the most generic scope. Then the Container can generate children in the next scope thanks to the SubContainer method.

A container is only able to build objects defined in its own scope, but it can retrieve objects in a more generic scope thanks to its parent. For example a Request container can retrieve an App object, but an App container can not retrieve a Request object.

If a Definition does not have a scope, the most generic scope will be used.

Scopes in practice

// Create a Builder with the default scopes (App, Request, SubRequest).
builder, _ := di.NewBuilder()

// Define an object in the App scope.
builder.Add(di.Def{
    Name: "app-object",
    Scope: di.App, // this line is optional, di.App is the default scope
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
})

// Define an object in the Request scope.
builder.Add(di.Def{
    Name: "request-object",
    Scope: di.Request,
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
})

// Build creates a Container in the most generic scope (App).
app := builder.Build()

// The App Container can create sub-containers in the Request scope.
req1, _ := app.SubContainer()
req2, _ := app.SubContainer()

// app-object can be retrieved from the three containers.
// The retrieved objects are the same: o1 == o2 == o3.
// The object is stored in app.
o1 := app.Get("app-object").(*MyObject)
o2 := req1.Get("app-object").(*MyObject)
o3 := req2.Get("app-object").(*MyObject)

// request-object can only be retrieved from req1 and req2.
// The retrieved objects are not the same: o4 != o5.
// o4 is stored in req1, and o5 is stored in req2.
o4 := req1.Get("request-object").(*MyObject)
o5 := req2.Get("request-object").(*MyObject)

More graphically, the containers could be represented like this:

The App container can only get the App object. A Request container or a SubRequest container can get either the App object or the Request object, possibly by using their parent. The objects are built and stored in containers that have the same scope. They are only created when they are requested.

Scopes and dependencies

If an object depends on other objects defined in the container, the scopes of the dependencies must be either equal or more generic compared to the object scope.

For example the following definitions are not valid:

di.Def{
    Name: "request-object",
    Scope: di.Request,
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
}

di.Def{
    Name: "object-with-dependency",
    Scope: di.App, // NOT ALLOWED !!! should be di.Request or di.SubRequest
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObjectWithDependency{
            Object: ctn.Get("request-object").(*MyObject),
        }, nil
    },
}

Container deletion

A definition can also have a Close function.

di.Def{
    Name: "my-object",
    Scope: di.App,
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
    Close: func(obj interface{}) error {
        // assuming that MyObject has a Close method that returns an error
        return obj.(*MyObject).Close() 
    },
}

This function is called when the Delete method is called on a Container.

// Create the Container.
app := builder.Build()

// Retrieve an object.
obj := app.Get("my-object").(*MyObject)

// Delete the Container, the Close function will be called on obj.
app.Delete()

Delete closes all the objects stored in the Container. Once a Container has been deleted, it becomes unusable.

It is important to always use Delete even if the objects definitions do not have a Close function. It allows to free the memory taken by the Container.

There are actually two delete methods: Delete and DeleteWithSubContainers

DeleteWithSubContainers deletes the children of the Container and then the Container. It does this right away. Delete is a softer approach. It does not delete the children of the Container. Actually it does not delete the Container as long as it still has a child alive. So you have to call Delete on all the children. The parent Container will be deleted when Delete is called on the last child.

You probably want to use Delete and close the children manually. DeleteWithSubContainers can cause errors if the parent is deleted while its children are still used.

Methods to retrieve an object

When a container is asked to retrieve an object, it starts by checking if the object has already been created. If it has, the container returns the already built instance of the object. Otherwise it uses the Build function of the associated definition to create the object. It returns the object, but also keeps a reference to be able to return the same instance if the object is requested again.

A container can only build objects defined in the same scope. If the container is asked to retrieve an object that belongs to a different scope. It forwards the request to its parent.

There are three methods to retrieve an object: Get, SafeGet and Fill.

Get

Get returns an interface that can be cast afterwards. If the object can not be created, the Get function panics.

obj := ctn.Get("my-object").(*MyObject)

SafeGet

Get is an easy way to retrieve an object. The problem is that it can panic. If it is a problem for you, you can use SafeGet. Instead of panicking, it returns an error.

objectInterface, err := ctn.SafeGet("my-object")
object, ok := objectInterface.(*MyObject)

Fill

The third and last method to retrieve an object is Fill. It returns an error if something goes wrong like SafeGet, but it may be more practical in some situations. It uses reflection to fill the given object. Using reflection makes it is slower than SafeGet.

var object *MyObject
err := ctn.Fill("my-object", &object)

Unscoped retrieval

The previous methods can retrieve an object defined in the same scope or a more generic one. If you need an object defined in a more specific scope, you need to create a sub-container to retrieve it. For example, an App container can not create a Request object. A Request container should be created to retrieve the Request object. It is logical but not always very practical.

UnscopedGet, UnscopedSafeGet and UnscopedFill work like Get, SafeGet and Fill but can retrieve objects defined in a more generic scope. To do so, they generate sub-containers that can only be accessed internally by these three methods. To remove these containers without deleting the current container, you can call the Clean method.

builder, _ := di.NewBuilder()

builder.Add(di.Def{
    Name: "request-object",
    Scope: di.Request,
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
    Close: func(obj interface{}) error {
        return obj.(*MyObject).Close()
    },
})

app := builder.Build()

// app can retrieve a request-object with unscoped methods.
obj := app.UnscopedGet("request-object").(*MyObject)

// Once the objects created with unscoped methods are no longer used,
// you can call the Clean method. In this case, the Close function
// will be called on the object.
app.Clean()

Panic in Build and Close functions

Panics in Build and Close functions of a definition are recovered and converted into errors. In particular that allows you to use the Get method in a Build function.

HTTP helpers

DI includes some elements to ease its integration in a web application.

The HTTPMiddleware function can be used to inject a container in an http.Request.

// create an App container
builder, _ := NewBuilder()
builder.Add(/* some definitions */)
app := builder.Build()

handlerWithDiMiddleware := di.HTTPMiddleware(handler, app, func(msg string) {
    logger.Error(msg) // use your own logger here, it is used to log container deletion errors
})

For each http.Request, a sub-container of the app container is created. It is deleted at the end of the http request.

The container can be used in the handler:

handler := func(w http.ResponseWriter, r *http.Request) {
    // retrieve the Request container with the C function
    ctn := di.C(r)
    obj := ctn.Get("object").(*MyObject)

    // there is a shortcut to do that
    obj := di.Get(r, "object").(*MyObject)
}

The handler and the middleware can panic. Do not forget to use another middleware to recover from the panic and log the errors.

Examples

The sarulabs/di-example repository is a good example to understand how DI can be used in a web application.

More explanations about this repository can be found in this blog post:

If you do not have time to check this repository, here is a shorter example that does not use the HTTP helpers. It does not handle the errors to be more concise.

package main

import (
    "context"
    "database/sql"
    "net/http"

    "github.com/sarulabs/di"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    app := createApp()
    defer app.Delete()

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Create a request and delete it once it has been handled.
        // Deleting the request will close the connection.
        request, _ := app.SubContainer()
        defer request.Delete()

        handler(w, r, request)
    })

    http.ListenAndServe(":8080", nil)
}

func createApp() di.Container {
    builder, _ := di.NewBuilder()

    builder.Add([]di.Def{
        {
            // Define the connection pool in the App scope.
            // There will be one for the whole application.
            Name:  "mysql-pool",
            Scope: di.App,
            Build: func(ctn di.Container) (interface{}, error) {
                db, err := sql.Open("mysql", "user:password@/")
                db.SetMaxOpenConns(1)
                return db, err
            },
            Close: func(obj interface{}) error {
                return obj.(*sql.DB).Close()
            },
        },
        {
            // Define the connection in the Request scope.
            // Each request will use its own connection.
            Name:  "mysql",
            Scope: di.Request,
            Build: func(ctn di.Container) (interface{}, error) {
                pool := ctn.Get("mysql-pool").(*sql.DB)
                return pool.Conn(context.Background())
            },
            Close: func(obj interface{}) error {
                return obj.(*sql.Conn).Close()
            },
        },
    }...)

    // Returns the app Container.
    return builder.Build()
}

func handler(w http.ResponseWriter, r *http.Request, ctn di.Container) {
    // Retrieve the connection.
    conn := ctn.Get("mysql").(*sql.Conn)

    var variable, value string

    row := conn.QueryRowContext(context.Background(), "SHOW STATUS WHERE `variable_name` = 'Threads_connected'")
    row.Scan(&variable, &value)

    // Display how many connections are opened.
    // As the connection is closed when the request is deleted,
    // the value should not be be higher than the number set with db.SetMaxOpenConns(1).
    w.Write([]byte(variable + ": " + value))
}

Migration from v1

DI v2 improves error handling. It should also be faster. Migrating to v2 is highly recommended and should not be too difficult. There should not be any more changes in the API for a long time.

Renamed elements

Some elements have been renamed.

A Context is now a Container.

The Context methods SubContext, NastySafeGet, NastyGet, NastyFill have been renamed. Their new names are SubContainer, UnscopedSafeGet, UnscopedGet, and UnscopedFill.

Definition is now Def. The AddDefinition of the Builder is now Add and can take more than one definition as parameter.

Definition Tags were removed in v2.0 but they are back in v2.1.

Errors

The Close function in a definition now returns an error.

The Container methods Clean, Delete and DeleteWithSubContainers also return an error.

Get

The Get method used to return nil if it could not retrieve the object. Now it panics with the error.

Logger

The Logger does not exist anymore. The errors are now directly handled by the retrieval functions.

// remove this line if you have it
builder.Logger = ...

Builder.Set

The Set method of the builder does not exist anymore. You should use the Add method and a Def.

di's People

Contributors

kentin14 avatar markusdosch avatar sarulabs avatar snovichkov avatar trivigy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

di's Issues

HTTPMiddleware returns http.HandlerFunc

Hi,

I'm developing web application using echo web framework and your di framework.

To use both, I should wrap di as middleware of echo, and it is something like this.

// DI.
multiWriter := io.MultiWriter(os.Stdout,logFile)

app := createApp(multiWriter)
defer app.Delete()

m := func(h http.Handler) http.Handler {
    return di.HTTPMiddleware(h, app, func(msg string){
        log.Println(msg)
    })
}

em := echo.WrapMiddleware(m)

e := echo.New()
e.Use(em)

The problme is echo.WrapMiddleware method takes func(http.Handler) http.Handler as parameter
and di.HTTPMiddleware returns http.HandlerFunc.

So I had to modified di.HTTPMiddleware like this as a quick fix.

func HTTPMiddleware(h http.Handler, app Container, logFunc func(msg string)) http.Handler {

    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // create a request container from tha app container
        ctn, err := app.SubContainer()
        if err != nil {
            panic(err)
        }
        defer func() {
            if err := ctn.Delete(); err != nil && logFunc != nil {
                logFunc(err.Error())
            }
        }()
        // call the handler with a new request
        // containing the container in its context
        h.ServeHTTP(w, r.WithContext(
            context.WithValue(r.Context(), ContainerKey("di"), ctn),
        ))
    })
}

I'm not sure this is good idea.
So please suggest good solution for this.

Thank you for this awesome library, anyway.

Should I define severices for each main package

I have a cmd directory in my project, with two sub-directory which they have their own main packages,
one is http server like the example you have written, the other one is long running console app, I have defined all Defs in one package with app and request scope, but in console app I do not have a request scope. I use the same slice of def in both main packages. my problem is for example in console app I want to get the repository in app scope but I defined it in request scope,in http server it works correct, but in console app it complains about that you can not use request scope service in app scope service, my long running console app is in app scope, should I have slices of def for each main package with different scope for repository def and also other defs.
thanks for great library.

Best way to go about passing/getting data from main package to another?

Hello there,
I would like to preface this by saying I am fairly new to Go, so I am still learning the tips and tricks on how to go about things. I had been wanting to learn Go for a while and since I had built a fairly complex Discord bot in Python I thought it would be a good learning experience to rewrite it in Go. That being said, I am a bit more used to C# and Python in which passing around data was no problem but I have been having to wrap my head around essentially only being able to reference from parent to children. I was quite happy when I came across this DI package though, so I have been focusing on trying to use it to the best of my ability.

That being said, I do have it implemented and working. I went by your example pretty closely and I tested that I was able to retrieve data from an object using the following:

// main/services
var Services = []di.Def{
	{
		Name: "configData",
		Build: func(ctn di.Container) (interface{}, error) {
			var cfg appconfig.MainSettings
			config := cfg.GetConfig()
			return config, nil
		},
	},
}


// main

type AppContext struct {
	Verifier *verifier.Verifier
}

func main() {
	var appContext AppContext

	builder, err := di.NewBuilder()
	if err != nil {
		logrus.Fatal(err.Error())
	}

	err = builder.Add(services.Services...)
	if err != nil {
		logrus.Fatal(err.Error())
	}

	app := builder.Build()
	defer app.Delete()

	verifierRun, err := appContext.Verifier.VerifierRun(app.Get("configData").(*appconfig.MainSettings))
	if err != nil {
		log.Println("error creating Bot session,", err)
	}

// --- so on and so forth ---

Now, my config stuff is all in main/appconfig then the above is in main/services (as I was going by your example), but I also have main/verifier and then main/verifier/cmdroutes. cmdroutes is using this package which helps make things a bit easier when making a Discord bot. The problem though is, I go to issue a command to the bot and the bot requires some info from my config in order to utilize the Discord API but I am not sure how to go about getting it into the cmdroutes package.

The particular command I was trying to test is called ListRoles, it has a named struct, and I thought if perhaps I were to do the following, that might work: The function looks like this, at least this is what it looks like currently in the middle of my testing:

type ListRoles struct {
	ctn di.Container
}

func (p *ListRoles) Handle(ctx *exrouter.Context) {

	guildObject, err := p.ctn.SafeGet("configData")
	if err != nil {
		log.Fatalf("Didn't work. : / ", err)
	}
	if guild, ok := guildObject.(*appconfig.MainSettings); ok {
		log.Infof("GuildID: %s", guild.Discord.Guild)
	} else {
		log.Fatalf("Also didn't work. : \ ", err)
	}

	guildRoles, err := ctx.Ses.GuildRoles(p.ctn.Get("configData").(*appconfig.MainSettings).Discord.Guild)
	if err != nil {
		log.Print("Could not get list of current roles", err)
	}

	roleTable := p.renderMarkDownTable(guildRoles)
	_, err = ctx.Reply(roleTable)
	if err != nil {
		log.Print("Something went wrong when handling listroles request", err)
	}
}

func NewListRoles() *ListRoles {
	return &ListRoles{}
}

Upon running that though I end up with:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x60 pc=0x71c61e]

Which comes from the first line of the above function.
Below is the "main application" which is main/verifier and where the above route/handler gets registered.

type Verifier struct {
}

type Config struct {
	Settings *appconfig.MainSettings
	Session  *discordgo.Session
	Routes   []cmdroutes.Route
	botId    string
}

func (vc *Config) registerRoutes(session *discordgo.Session, Routes ...cmdroutes.Route) {
	router := exrouter.New()

	cmdroutes.RegisterRoutes(
		router,
		Routes...,
	)

	session.AddHandler(func(_ *discordgo.Session, m *discordgo.MessageCreate) {
		log.Printf("Message %v", m.Content)
		log.Printf("Message %v", m.Type)
		_ = router.FindAndExecute(vc.Session, vc.Settings.System.CommandPrefix, session.State.User.ID, m.Message)
	})
}

func (v *Verifier) VerifierRun(s *appconfig.MainSettings) (*Config, error) {
	session, err := discordgo.New("Bot " + s.System.Token)
	if err != nil {
		fmt.Println("Error connecting to server: ", err)
		return nil, err
	}

	settings := &Config{Settings: s,
		Session: session,
		Routes: []cmdroutes.Route{
			cmdroutes.NewSubRoute(),
			cmdroutes.NewUser(),
			cmdroutes.NewDirectMessage(),
			cmdroutes.NewPing(),
			cmdroutes.NewListRoles()}}

	var logLevel int
	switch settings.Settings.System.ConsoleLogLevel {
	case "DEBUG":
		logLevel = discordgo.LogDebug
	case "INFO":
		logLevel = discordgo.LogInformational
	case "WARNING":
		logLevel = discordgo.LogWarning
	case "ERROR":
		logLevel = discordgo.LogError
	default:
		logLevel = discordgo.LogError
	}

	settings.Session.LogLevel = logLevel
	settings.registerRoutes(settings.Session, settings.Routes...)

 //--------- so on and so forth
}

I was hoping that perhaps you might be able to point me in the right direction on what would be the best way to go about trying to get my DI container into the func (p *ListRoles) Handle(ctx *exrouter.Context) function? I am going to have many of them and each one is going to need access to the info within the containers, so I am hoping that I can try to find the most "proper" way to do it, but also the most efficient.

If you happen to have any insight or ideas you might be able to share on what I should / could try, I would greatly appreciate it!

Thanks,
-MH

Memory leak when definition unshared true

I has issue when make looping and get object with unshared set true. memory not release after function finish. Maybe because when get object, that object save in ctn.

How to use it in Gin

Hi, I have some problems using this in Gin

main.go

	builder, err := di.NewBuilder()
	if err != nil {
		fmt.Print(err.Error())
		return
	}

	_ = builder.Set("config", &GlobalConfig)

	err = builder.Add(container.Services...)
	if err != nil {
		fmt.Print(err.Error())
                return
	}

	app := builder.Build()

	defer app.Delete()
        ......

services.go

var Services = []di.Def{
	{
		Name:  "nsq",
		Scope: di.App,
		Build: func(app di.Container) (interface{}, error) {
			c,_ := nsq.NewProducer(app.Get("config").(*conf.Config).NsqAddr, nsq.NewConfig())
			return &producer.Producer{
				NSQClient : c,
			}, nil
		},
	},
}

user.go

func IntegralByLogin(c *gin.Context) {
	fmt.Print(di.Get(c.Request, "nsq").(*producer.Producer).Test())
}

result:
could not get the container from the given *http.Request

When using app.subcontainer is each one executed in it's own goroutine?

Part of what I am using this for is for DB connections similar to what you have in the example, but I wanted to check if I needed to try and handle threading on my own or if this takes care of any threading already?

Here was how I was planning on doing it.

	{
		// --- Creates database connection object ----------------------------------------------------------------------
		Name:  "dbConn",
		Scope: di.App,
		Build: func(ctn di.Container) (interface{}, error) {
			var db appconfig.DbSettings
			var conn components.DbConfig
			dbconfig := db.GetDbConfig()
			dbConn := conn.ConnectDB(dbconfig)
			return dbConn, nil
		},
		Close: func(obj interface{}) error {
			return obj.(*components.DbConfig).Xorm.Close()
		},
	},
	{
		// --- Uses database connection object and returns a connection session ----------------------------------------
		Name:  "db",
		Scope: di.Request,
		Build: func(ctn di.Container) (interface{}, error) {
			conn := ctn.Get("dbConn").(*components.DbConfig).Xorm
			return conn, nil
		},
		Close: func(obj interface{}) error {
			return obj.(*components.DbConfig).Xorm.Close()
		},
	},

Thanks,
-MH

Outside parameters for definition

I hope this repo is still in maintenance.
My use case is, for every incoming request, I will generate a unique id for logging. There will be a Logging Definition with Request Scope that needs to be initialized a new instance for every request. This Logging Definition will use the generated unique id for logging.
How can I inject this unique id into Logging Definition or at least into Request Scope context ๐Ÿ˜„
I hope to hear response from you

Is there a concept of Transient

We have di.App and di.Request, but what about di.Transient.

This is taken from what the DI in asp.net core does.

I would like to register an object in the DI with a transient scope, which means that any Get will do a new as opposed to looking it up in a map to see if it has already been created.

A transient object can pull singleton objects from the same container, but not di.Request objects. A di.Request object can pull both singletons and transients.

Authentication middleware example

Do you have an example on how to implement a authentication middleware that only authenticates part of the endpoints and not all of them?

Thanks in advance.
//Tagnard

Tags on v2

Hello, in my projects I actively use tags in definitions. Since you deleted them in the second version, I cannot properly migrate, could you return this functionality, it is vital for my projects.

Request Scope Isolation question

Is the following behavior expected or Is there a way to use the library in this scenario?

When using in a web application, and a request is made to the server, should the X, Y, Z definition still build if the request does not depend on the X, Y, Z definition?

The reason I am asking is because I have a di.Request scope that is defined to trigger an sql.Transaction for certain services that require a transaction. However, is causing "db. tx" definition to trigger each time a request is made even though "db. tx" is not a dependency for the request made.

Thanks for the library.

Feature Request: Add by Type, GetByType and GetManyByType

First off, nice library. I was able to add these features and not have to rearchitect anything in the original library. My version is located here

If you accept these features, I can do a proper fork and PR so you can see how I did it.

New Features

The following are non breaking changes to sarulabs/di.

SafeGetByType

// SafeGetByType retrieves the last object added from the Container.
// The object has to belong to this scope or a more generic one.
// If the object does not already exist, it is created and saved in the Container.
// If the object can not be created, it returns an error.
SafeGetByType(rt reflect.Type) (interface{}, error)

GetByType

// GetByType is similar to SafeGetByType but it does not return the error.
// Instead it panics.
GetByType(rt reflect.Type) interface{}

SafeGetManyByType

// SafeGetManyByType retrieves an array of objects from the Container.
// The objects have to belong to this scope or a more generic one.
// If the objects do not already exist, it is created and saved in the Container.
// If the objects can not be created, it returns an error.
SafeGetManyByType(rt reflect.Type) ([]interface{}, error)

GetManyByType

// GetManyByType is similar to SafeGetManyByType but it does not return the error.
// Instead it panics.
GetManyByType(rt reflect.Type) []interface{}

Just like dotnetcore, I would like to register a bunch of services that all implement the same interface. I would like to get back an array of all registered objects, and to do that I need to ask for them by type

For efficiency, type validation is done during registration. After that it should just be lookups.
When you do a GetByType, don't keep calling reflect to get a type of what is a compliled type. do it once and put it in a map.

Registration

type DEF struct

// Def contains information to build and close an object inside a Container.
type Def struct {
	Build            func(ctn Container) (interface{}, error)
	Close            func(obj interface{}) error
	Name             string //[ignored] if Type is used this is overriden and hidden.
	Scope            string
	Tags             []Tag
	Type             reflect.Type //[optional] only if you want to claim that this object also implements these types.
	ImplementedTypes TypeSet
	Unshared         bool
}

Two new fields where added to the Def struct.

	Type             reflect.Type
	ImplementedTypes TypeSet

Type: is the type of the object being registered.
ImplementedTypes: is the types that this object either is or implements

Only the Type option is needed to register and it is automatically added as an implemented type. The ImplementedTypes option is primarily for claiming that the added type supports a given set of interfaces. If this option is added, the original Type is automatically added to the ImplementedTypes set.

The following code will return an error if the added type DOES NOT implemented the ImplementedTypes that were claimed.

type ISomething interface {
	GetName() string
	SetName(name string)
}

type Service struct {
	name            string
}
// SetName ...
func (s *Service) SetName(in string) {
	s.name = in
}

// SetName ...
func (s *Service) GetName() string {
	return s.name
}

func AddTransientService(builder *di.Builder) {
	log.Info().Msg("IoC: AddTransientService")

	types := di.NewTypeSet()
	inter := di.GetInterfaceReflectType((*exampleServices.ISomething)(nil))
	types.Add(inter)
	
	builder.Add(di.Def{
		Name:             "[overidden and hidded if added by Type, can be empty]",
		Scope:            di.App,
		ImplementedTypes: types, //[optional] only if you want to claim that this object also implements these types.
		Type:             reflect.TypeOf(&Service{}),
		Unshared: true,
		Build: func(ctn di.Container) (interface{}, error) {
			service := &Service{
			}
			return service, nil
		},
	})
}

Retrieval

// please put this into a lookup map
inter := di.GetInterfaceReflectType((*exampleServices.ISomething)(nil))

dd := ctn.GetManyByType(inter)
for _, d := range dd {
  ds := d.(exampleServices.ISomething)
  ds.SetName("rabbit")
  log.Info().Msg(ds.GetName())
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.