Giter Site home page Giter Site logo

ckgrafico / inversify-props Goto Github PK

View Code? Open in Web Editor NEW
84.0 3.0 9.0 6.94 MB

Wrapper of Inversify to inject your dependencies in the components, made with TypeScript and compatible with Vue, React and other component libraries.

License: MIT License

TypeScript 96.11% JavaScript 3.89%
injection dependency-injection component vue react polymer lit-element

inversify-props's People

Contributors

aspearman avatar ckgrafico avatar dependabot[bot] avatar rdhainaut avatar sobolevn 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

Watchers

 avatar  avatar  avatar

inversify-props's Issues

[Question] Is there a way to pass parameters to a concrete type when registering?

Assuming I have the following:

interface IMyService {
	doTheThing(): void;
}

class MyService extends IMyService {
	 constructor(baseUrl: string) {
		this.baseUrl = baseUrl;
	}
	
	doTheThing(): void {
		//Do something here
	}
	
	private baseUrl!: string;
}

Is there a way to pass baseUrl when registering MyService with the container? Something like: container.addTransient<IMyService>(() => new MyService("BaseUrl"));? Coming from C# this is typically how it's done so I might just be approaching this completely wrong.

I want to set baseUrl at the time of registering as it will change depending on the environment.

*bug* cid :: Not clearing cached Symbol, when renamed all interfaces names.

Hi there,

So, the issue is that, initially I added singletons for my application such as :

...
container.addSingleton<ISomeService>(SomeService);
container.addSingleton<ISomeOtherService>(SomeOtherService);
....

In tests, I mocked these interfaces and it worked fine.

Now, I renamed these services interfaces such as:

container.addSingleton<SomeServiceInterface>(SomeService);
container.addSingleton<SomeOtherServiceInterface>(SomeOtherService);

Now, in tests when I have mocked these interfaces and overriding instances of these interfaces, it is throwing error that could not unbind serviceIdentifier: undefined.
image

When I console.log(cid), it gave me the previously registered Service sysmbols i.e. ISomeService, instead it should have been updated to SomeServiceInterface.

Please look into this.

what's the meaning of this line?

Reflect.deleteProperty[key];

I copy this line to my file but got a error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '(target: object, propertyKey: string | number | symbol) => boolean'.
  No index signature with a parameter of type 'string' was found on type '(target: object, propertyKey: string | number | symbol) => boolean'.ts(7053)

Reflect.hasOwnMetadata is not a function

injectable.js?719e:7 Uncaught TypeError: Reflect.hasOwnMetadata is not a function

injectable.js?719e:7 Uncaught TypeError: Reflect.hasOwnMetadata is not a function
at eval (injectable.js?719e:7)
at Module.__decorate (tslib.es6.js?9ab4:56)

Error when I use generics

Hi

Error when I use generics throw an exception

Uncaught Error: Cannot apply @Injectable decorator multiple times.
at eval (injectable.js?719e:8)
at eval (inject.helper.js?5df8:10)
at DecorateConstructor (Reflect.js?98db:541)
at Object.decorate (Reflect.js?98db:130)
at _decorate (decorator_utils.js?66d7:42)
at Object.decorate (decorator_utils.js?66d7:55)
at Container.addSingleton (container.js?7644:42)
at containerBuilder (app.container.ts?1e2a:26)
at new AppModule (main.ts?bc82:13)
at eval (main.ts?bc82:30)

This is my code

import { container, injectable } from 'inversify-props';

interface Test {
	id: string;
}

interface TestChild extends Test {
	name: string;
}

interface ServiceInterface<T extends Test> {
	get(): Promise<T>;
}

@injectable()
class Services implements ServiceInterface<TestChild> {
	get(): Promise<TestChild> {
		throw new Error('Method not implemented.');
	}
}

export function containerBuilder(): void {
	container.addSingleton<ServiceInterface<TestChild>>(Services);
}

How can I do to make it work?

Inject decorator doesn't work in javascript

Hello, first I want to say thanks for this tool.

I'm making some sample projects to use inversify-props with Nuxt, both in Typescript and Javascript. I've succsesfully achieved what I wanted to try in this sample repo with Typescript.

The thing is that when I try to use @inject('SomeService') someService in a javascript es6 class, the property is not created (someService is undefined), but if I use someService = container.get(cid.SomeService) then it works fine.

I don't know if it's my fault or something else.

All help would be appreciated, thanks in advance !

Injecting into injectable doesn't seem to work

Hi,

I have a client and an injectable service in a Vue project, and I want to inject the client into the service:

@injectable()
export class Service {
    @inject(CONTAINER_IDS.Client) private client!: Client
}

This in itself should not be an issue since it is done in the vue example https://github.com/CKGrafico/inversify-props/tree/master/examples/vue.
Both client and service are added to the container like so:

container.addSingleton<Client>(Client, CONTAINER_IDS.Client)
container.addSingleton<Service>(Service, CONTAINER_IDS.Service)

Client is just an empty injectable:

@injectable()
export class Client {
}

But the main view is not displayed. Neither client nor service are used anywhere else. Firefox gives the following error:

TypeError: _container__WEBPACK_IMPORTED_MODULE_3__.default is undefined

And in Chrome:

Uncaught TypeError: Cannot read property 'Client' of undefined

I have uploaded the sample project here: https://github.com/dazzling-babbage/inversify-issue
The sample project is extracted from a real project, which is why there are so many dependencies etc.

You can use npm run serve to run it. It should just display the text YAY!, but displays a white page instead due to the errors above. If you comment out container.addSingleton<Service>(Service, CONTAINER_IDS.Service) in container.ts it runs fine, the same if you comment out @inject(CONTAINER_IDS.Client) private client!: Client in service.ts.

I am really at a loss as to what I am doing wrong. It would be great if you could look into this.

Thanks a lot

How can I use this library using my own inversify container?

Hey! Great utility library!

I would like to have my own container using inversify and somehow be able to tell inversify-props to hook up with an existing container. For instance:

import { Container } from 'inversify'
import { container as containerProps } from 'inversify-props'

export const TYPES = {
  WINDOW: Symbol.for('WINDOW')
}

const container = new Container()
container.bind<Window>(TYPES.WINDOW).toConstantValue(window)
containerProps.use(container) // Or something similar
export { container }

And then in the component:

export default class extends Component {
  @inject(TYPES.WINDOW) window: Window
}

Is this possible?

Named injections do not work

WIth [email protected]

import { inject } from 'inversify-props'
import { named } from 'inversify'

class ...
    @inject(Symbols.feathers)
    @named('hubService')
    feathers

does not work but

import { container } from 'inversify-props'
...
this.feathers = container.getNamed(Symbols.feathers, 'hubService')

does work

*bug* IE 11 Not supported ::

Hi there,

In IE11, we uses polyfills to support Symbol (i.e. core-js/es/symbol), now in your codebase I noticed you are checking the type of symbol as below.

image

As because of polyfills, this will be treated as object type, 'cause of which it will never find the realCid and won't resolve the dependancy.

Please look into this.

Singleton scope doesn't seem to work

Hi,

I've got an Auth Service which I use to track an authenticated user.

When declaring the service like:

container.addSingleton<IAuthService>(AuthService)

The constructor is called twice on AuthService when the service is injected via

@Inject()
private readonly authService!: AuthService

However, if I use the root container instead, and bind the module like:

container.bind<AuthService>(AuthService).toSelf().inSingletonScope()

then inject it like:

private readonly authService: AuthService = container.get(AuthService)

The AuthService constructor is only called once and the data I entered when logging my user in is still present (as the instance isn't recreated).

Am I misunderstanding your singleton implementation or is this a bug?

EDIT: I've just been playing around and it's worth noting, the first time I'm calling the service, I'm doing do via container.resolve(AuthService) which might explain why I get a second instance because if I try container.get(AuthService) and have I've bound the service using the container.addSingleton<IAuthService>(AuthService) method, I get an error saying the AuthService isn't bound.

I guess on that note then, I should be asking - why isn't the service bound when calling container.get(AuthService) as I would have expected it to be bound because of container.addSingleton<IAuthService>(AuthService)

[Question] How to use Jest

I am wondering if there is a way to use Jest for mocking dependencies instead write custom mock classes and use mockSingleton or mockTransient?

Issue with 1.4.0

Hi, I have some problems on upgrade from 1.3.5 to 1.4.0

I made the upgrade and changed all references to "Inject" (with a capital I) to "inject" as per the updated documentation.

However on run I get:

Error: @inject called with undefined this could mean that the class undefined has a circular dependency problem. You can use a LazyServiceIdentifer to overcome this limitation.

Is this a bug or is there something else I need to change for 1.4.0? Everything was working perfectly before the upgrade.

I expect this is unrelated, but during build I also now get these warnings from the parceljs bundler, which didn't happen before:

⚠️  Could not load source file "../src/index.ts" in source map of "../node_modules/inversify-props/dist/index.js".
⚠️  Could not load source file "../src/index.ts" in source map of "../node_modules/inversify-props/dist/index.js".
⚠️  Could not load source file "../../src/lib/helpers.ts" in source map of "../node_modules/inversify-props/dist/lib/helpers.js".
⚠️  Could not load source file "../../src/lib/container.ts" in source map of "../node_modules/inversify-props/dist/lib/container.js".

Error: No matching bindings found for serviceIdentifier: Symbol()

In production build I get the following error with injecting a service in a Vue component
vue.runtime.esm.js:1888 Error: No matching bindings found for serviceIdentifier: Symbol(TestService).

In dev build everything works.

Production build with:
vue-cli-service build

Dev build with:
vue-cli-service serve or vue-cli-service build --mode development

I made a simple project to show my issue:

TestVueProject.zip

Error with Vue in production.

Hello,
I'm having an error when I build my Vue Application. So, when I run my Vue Application in development mode it doesn't throw the error but when I build it to production, I keep having this problem. I don't know why. I have spent hours trying to figure this and googled a lot but could not understand the problem.

Error:
"No matching bindings found for serviceIdentifier: Symbol(IAppConfig)"

My Code:

export class ContainerBuilder {
    build() {
        container.addSingleton<IAppConfig>(AppConfig);
    }
}
//===========
AppConfig.ts

@injectable()
export class AppConfig implements IAppConfig {
    get HostApi() {
        return this.hostApi;
    }
}

export interface IAppConfig {
    readonly HostApi: string | undefined;
}

Vue-CLI Production Error

Hello, I think I always ask stuff that are not really a bug with the library, but I don't know where to ask. So I apologize if this is too dumb.

I'm trying to build a vue app for production. The documentation says that I have to configure Terser plugin so I did. Put this inside vue.config.js

  const TerserPlugin = require("terser-webpack-plugin");
  module.exports = {
  //... other configs
    configureWebpack: (config) => {
      config.optimization = {
        minimize: true,
        minimizer: [
          new TerserPlugin({
            terserOptions: {
              keep_classnames: true,
              keep_fnames: true,
            },
          }),
        ],
      };
    },
  }

But I still get a blank page after building and the following error:

Uncaught TypeError: o is undefined
    generateIdName id.helper.js:19
    cleanParameter parameters.helper.js:26
    injectParameterDecorator inject.helper.js:41
    inject inject.helper.js:21
    __param tslib.es6.js:61
    DecorateConstructor Reflect.js:541
    decorate Reflect.js:130
    __decorate tslib.es6.js:55
    f112 HttpService.ts:53
    Webpack 5
        __webpack_require__
        0
        __webpack_require__
        <anonymous>
        <anonymous>

Note: Before I configured TerserPlugin the error was a bit different. It said TypeError: e is undefined
Note2: It works completely fine in development mode

[Documentation][Vue-cli][TerserPlugin] Symbol not found in production

I write this issue to improve the documentation.
I know there is a paragraph on that but it was really no obvious.

First my issue is "a duplicate" of #25

I m using inversify props in Vue project.
I m using Vue cli.
Vue cli "hide" a lot of builder config and i have learnt that is using "Terser" plugin under the hood.
Generally, I don t must change any option about this except for this lib.

To fix this issue, i have added the following config in my Vue.config.js file

module.exports = {
    configureWebpack: (config) => {
      // See: https://github.com/CKGrafico/inversify-props#how-to-configure-uglify-or-terser
      config.optimization = {
        minimize: true,
        minimizer: [
          new TerserPlugin({
            terserOptions: {
              compress: {
                arrows: false,
                collapse_vars: false,
                comparisons: false,
                computed_props: false,
                hoist_funs: false,
                hoist_props: false,
                hoist_vars: false,
                inline: false,
                loops: false,
                negate_iife: false,
                properties: false,
                reduce_funcs: false,
                reduce_vars: false,
                switches: false,
                toplevel: false,
                typeofs: false,
                booleans: true,
                if_return: true,
                sequences: true,
                unused: true,
                conditionals: true,
                dead_code: true,
                evaluate: true
              },
              mangle: {
                safari10: true
              },
              // inversify props
              keep_classnames: true,
              keep_fnames: true
            },
            sourceMap: true,
            cache: true,
            parallel: true,
            extractComments: false
          })
        ]
      };
    }
}

Uncaught Error: @inject called with undefined this could mean that the class undefined has a circular dependency problem

i am writing a simple electron + vue + typescript app. when debugging in vscode ( which attaches to webpack debugger server), inversify-props works without problem. i can get the result as expected.

无标题1

but when i run electron-vue-ts-element.exe --enable-logging (excutable binary electron-vue-ts-element.exe is generated by yarn electron:build ), that error is printed in stderr.

无标题2

two dependency chains:

HelloWorld.vue -> AnotherWorkerService(non-vue-component) -> WorkerService(non-vue-component)
HelloWorld.vue -> WorkerService(non-vue-component)

inversify-props: "^1.4.3"

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.