Explore all Dependency Injection open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Dependency Injection

guice

Guice 5.1.0

InversifyJS

v6.0.1

wire

0.5.0

Swinject

v2.8.0

Autofac

v6.3.0

Popular Libraries in Dependency Injection

dep

by golang doticongodoticon

star image 13170 doticonNOASSERTION

Go dependency management tool experiment (deprecated)

guice

by google doticonjavadoticon

star image 10791 doticonApache-2.0

Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 8 and above, brought to you by Google.

InversifyJS

by inversify doticontypescriptdoticon

star image 8776 doticonMIT

A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.

dagger

by square doticonjavadoticon

star image 7274 doticonApache-2.0

A fast dependency injector for Android and Java.

wire

by google doticongodoticon

star image 6383 doticonApache-2.0

Compile-time Dependency Injection for Go

u2020

by JakeWharton doticonjavadoticon

star image 5740 doticonApache-2.0

A sample Android app which showcases advanced usage of Dagger among other open source libraries.

Swinject

by Swinject doticonswiftdoticon

star image 4802 doticonMIT

Dependency injection framework for Swift with iOS/macOS/Linux

Autofac

by autofac doticoncsharpdoticon

star image 3843 doticonMIT

An addictive .NET IoC container

dependency-injection

by symfony doticonphpdoticon

star image 3706 doticonMIT

The DependencyInjection component allows you to standardize and centralize the way objects are constructed in your application.

Trending New libraries in Dependency Injection

VContainer

by hadashiA doticoncsharpdoticon

star image 666 doticonMIT

The extra fast, minimum code size, GC-free DI (Dependency Injection) library running on Unity Game Engine.

stronginject

by YairHalberstadt doticoncsharpdoticon

star image 621 doticonMIT

compile time dependency injection for .NET

spaghetti

by adonovan doticongodoticon

star image 621 doticonBSD-2-Clause

Spaghetti: a dependency analysis tool for Go packages

jab

by pakrym doticoncsharpdoticon

star image 595 doticonMIT

C# Source Generator based dependency injection container implementation.

Lazybones

by skydoves doticonkotlindoticon

star image 271 doticonApache-2.0

😴 A lazy and fluent syntactic sugar for Android and ViewModel Lifecycle properties.

mandarinets

by mandarineorg doticontypescriptdoticon

star image 198 doticonMIT

Mandarine.TS is a typescript, decorator-driven framework that allows you to create server-side applications. Mandarine.TS provides a range of built-in solutions such as Dependency Injection, Components, ORM and more. Under its umbrella, Mandarine.TS has 4 modules: Core, Data, Security and MVC, these modules will offer you the requirements to build a Mandarine-powered application.

android-hilt

by googlecodelabs doticonkotlindoticon

star image 158 doticonApache-2.0

BlueHatIL-2020

by FuzzySecurity doticoncsharpdoticon

star image 128 doticon

BlueHatIL 2020 - Staying # and Bringing Covert Injection Tradecraft to .NET

NINA

by NtRaiseHardError doticoncdoticon

star image 113 doticon

NINA: No Injection, No Allocation x64 Process Injection Technique

Top Authors in Dependency Injection

1

autofac

14 Libraries

star icon4502

2

google

6 Libraries

star icon19999

3

microsoft

4 Libraries

star icon3152

4

MicrosoftDocs

4 Libraries

star icon8

5

jeremybytes

4 Libraries

star icon25

6

auraphp

4 Libraries

star icon422

7

googlecodelabs

4 Libraries

star icon337

8

codegangsta

4 Libraries

star icon940

9

googlearchive

3 Libraries

star icon83

10

lukaspili

3 Libraries

star icon276

1

14 Libraries

star icon4502

2

6 Libraries

star icon19999

3

4 Libraries

star icon3152

4

4 Libraries

star icon8

5

4 Libraries

star icon25

6

4 Libraries

star icon422

7

4 Libraries

star icon337

8

4 Libraries

star icon940

9

3 Libraries

star icon83

10

3 Libraries

star icon276

Trending Kits in Dependency Injection

No Trending Kits are available at this moment for Dependency Injection

Trending Discussions on Dependency Injection

dependency injection life cycle for IDisposable classes in .NET core

How to use appsettings.json in Asp.net core 6 Program.cs file

Android Build Error: "lStar not found..."

How to register ServiceBusClient for dependency injection?

How to create beans dynamically using a DI framework

What is the difference between static class and singleton in .net mvc project?

.NET Core Dependency Injection how to handle multiple objects

Does using Spring boot with javafx will consume a lot of memory?

.Net 6 Console app: WebApplication.CreateBuilder vs Host.CreateDefaultBuilder

Android Instrumented tests with KodeIn

QUESTION

dependency injection life cycle for IDisposable classes in .NET core

Asked 2022-Mar-29 at 09:28

I want to know, what is the best way to dispose the all IDisposable object after the request done.

  • AddTransient<T> - adds a type that is created again each time it's requested.
  • AddScoped<T> - adds a type that is kept for the scope of the request.
  • AddSingleton<T> - adds a type when it's first requested and keeps hold of it.

So, singleton could not be a good choice because it will disposes after app shot down. but scope and transient are good candidates. I have a repository which I want to create a connection with my db like this:

1public class Dapperr : IDapper  
2    {  
3        private readonly IConfiguration _config;  
4        private string Connectionstring = &quot;DefaultConnection&quot;;  
5  
6        public  Dapperr(IConfiguration config)  
7        {  
8            _config = config;  
9        }  
10        public void Dispose()  
11        {  
12             
13        }  
14  
15        
16        public T Get&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)  
17        {  
18            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
19            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).FirstOrDefault();  
20        }  
21  
22        public List&lt;T&gt; GetAll&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
23        {  
24            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
25            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).ToList();  
26        }  
27}
28

Now In my start up I'm going to add dependency injection:

1public class Dapperr : IDapper  
2    {  
3        private readonly IConfiguration _config;  
4        private string Connectionstring = &quot;DefaultConnection&quot;;  
5  
6        public  Dapperr(IConfiguration config)  
7        {  
8            _config = config;  
9        }  
10        public void Dispose()  
11        {  
12             
13        }  
14  
15        
16        public T Get&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)  
17        {  
18            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
19            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).FirstOrDefault();  
20        }  
21  
22        public List&lt;T&gt; GetAll&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
23        {  
24            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
25            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).ToList();  
26        }  
27}
28services.AddScoped&lt;IDapper, Dapperr&gt;();
29

I want to know if I am allow to remove All those using scop because of adding scope dependency. for example like this:

1public class Dapperr : IDapper  
2    {  
3        private readonly IConfiguration _config;  
4        private string Connectionstring = &quot;DefaultConnection&quot;;  
5  
6        public  Dapperr(IConfiguration config)  
7        {  
8            _config = config;  
9        }  
10        public void Dispose()  
11        {  
12             
13        }  
14  
15        
16        public T Get&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)  
17        {  
18            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
19            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).FirstOrDefault();  
20        }  
21  
22        public List&lt;T&gt; GetAll&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
23        {  
24            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
25            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).ToList();  
26        }  
27}
28services.AddScoped&lt;IDapper, Dapperr&gt;();
29public class Dapperr : IDapper  
30    {  
31        private readonly IConfiguration _config;  
32        private string Connectionstring = &quot;DefaultConnection&quot;;  
33    private readonly IDbConnection db ;
34        public  Dapperr(IConfiguration config)  
35        {  
36            _config = config;
37         db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
38        }  
39        
40        
41        public T Get&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)  
42        {  
43            
44            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).FirstOrDefault();  
45        }  
46
47        public List&lt;T&gt; GetAll&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
48        {  
49             
50            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).ToList();  
51        }
52  
53    }
54

does the sql connection dispose after request ended or I still need to use using?

ANSWER

Answered 2022-Mar-29 at 09:28

After reading the comments I got that, I have to set the the interface as IDisposable to dispose the connection, so I changed my code like this:

1public class Dapperr : IDapper  
2    {  
3        private readonly IConfiguration _config;  
4        private string Connectionstring = &quot;DefaultConnection&quot;;  
5  
6        public  Dapperr(IConfiguration config)  
7        {  
8            _config = config;  
9        }  
10        public void Dispose()  
11        {  
12             
13        }  
14  
15        
16        public T Get&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)  
17        {  
18            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
19            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).FirstOrDefault();  
20        }  
21  
22        public List&lt;T&gt; GetAll&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
23        {  
24            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
25            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).ToList();  
26        }  
27}
28services.AddScoped&lt;IDapper, Dapperr&gt;();
29public class Dapperr : IDapper  
30    {  
31        private readonly IConfiguration _config;  
32        private string Connectionstring = &quot;DefaultConnection&quot;;  
33    private readonly IDbConnection db ;
34        public  Dapperr(IConfiguration config)  
35        {  
36            _config = config;
37         db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
38        }  
39        
40        
41        public T Get&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)  
42        {  
43            
44            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).FirstOrDefault();  
45        }  
46
47        public List&lt;T&gt; GetAll&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
48        {  
49             
50            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).ToList();  
51        }
52  
53    }
54public interface IDapper : IDisposeable
55{
56    ... 
57}
58

then in my repo, I implemented dispose method:

1public class Dapperr : IDapper  
2    {  
3        private readonly IConfiguration _config;  
4        private string Connectionstring = &quot;DefaultConnection&quot;;  
5  
6        public  Dapperr(IConfiguration config)  
7        {  
8            _config = config;  
9        }  
10        public void Dispose()  
11        {  
12             
13        }  
14  
15        
16        public T Get&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)  
17        {  
18            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
19            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).FirstOrDefault();  
20        }  
21  
22        public List&lt;T&gt; GetAll&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
23        {  
24            using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
25            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).ToList();  
26        }  
27}
28services.AddScoped&lt;IDapper, Dapperr&gt;();
29public class Dapperr : IDapper  
30    {  
31        private readonly IConfiguration _config;  
32        private string Connectionstring = &quot;DefaultConnection&quot;;  
33    private readonly IDbConnection db ;
34        public  Dapperr(IConfiguration config)  
35        {  
36            _config = config;
37         db = new SqlConnection(_config.GetConnectionString(Connectionstring));  
38        }  
39        
40        
41        public T Get&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)  
42        {  
43            
44            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).FirstOrDefault();  
45        }  
46
47        public List&lt;T&gt; GetAll&lt;T&gt;(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
48        {  
49             
50            return db.Query&lt;T&gt;(sp, parms, commandType: commandType).ToList();  
51        }
52  
53    }
54public interface IDapper : IDisposeable
55{
56    ... 
57}
58public class Dapperr : IDapper  
59{  
60    private readonly IConfiguration _config;  
61    private string Connectionstring = &quot;DefaultConnection&quot;;  
62    private readonly IDbConnection db;
63    
64    public  Dapperr(IConfiguration config)  
65    {  
66        _config = config;
67        db = new SqlConnection(_config.GetConnectionString(Connectionstring));
68    }  
69    
70    public T Get&lt;T&gt;(
71        string sp,
72        DynamicParameters parms,
73        CommandType commandType = CommandType.Text)  
74    {  
75        return db.Query&lt;T&gt;(sp, parms, commandType: commandType).FirstOrDefault();  
76    }  
77
78    public List&lt;T&gt; GetAll&lt;T&gt;(string sp, DynamicParameters parms) =&gt;
79        db.Query&lt;T&gt;(sp, parms, commandType: commandType).ToList();  
80    
81    public void Dispose()
82    {
83        db?.dispose(); 
84    }
85}
86

After debugging, I saw this Dispose method is called and connection disposed. I'm not sure this is the best practice but by these changes I only wrote the connection config once and all my using blocs deleted. I think this would be good for light requests.

Source https://stackoverflow.com/questions/71646149

QUESTION

How to use appsettings.json in Asp.net core 6 Program.cs file

Asked 2022-Feb-25 at 21:39

I'm trying to access appsettings.json in my Asp.net core v6 application Program.cs file, but in this version of .Net the Startup class and Program class are merged together and the using and another statements are simplified and removed from Program.cs. In this situation, How to access IConfiguration or how to use dependency injection for example ?

Edited : Here is my default Program.cs that Asp.net 6 created for me

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =&gt;
5{
6    options.Configuration = &quot;localhost:6379&quot;;
7});
8
9builder.Services.AddSwaggerGen(c =&gt;
10{
11    c.SwaggerDoc(&quot;v1&quot;, new() { Title = &quot;BasketAPI&quot;, Version = &quot;v1&quot; });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;BasketAPI v1&quot;));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24

For example , I want to use appsettings.json instead of hard typed connectionstring in this line :

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =&gt;
5{
6    options.Configuration = &quot;localhost:6379&quot;;
7});
8
9builder.Services.AddSwaggerGen(c =&gt;
10{
11    c.SwaggerDoc(&quot;v1&quot;, new() { Title = &quot;BasketAPI&quot;, Version = &quot;v1&quot; });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;BasketAPI v1&quot;));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24options.Configuration = &quot;localhost:6379&quot;;
25

ANSWER

Answered 2021-Sep-30 at 11:13

Assuming an appsettings.json

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =&gt;
5{
6    options.Configuration = &quot;localhost:6379&quot;;
7});
8
9builder.Services.AddSwaggerGen(c =&gt;
10{
11    c.SwaggerDoc(&quot;v1&quot;, new() { Title = &quot;BasketAPI&quot;, Version = &quot;v1&quot; });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;BasketAPI v1&quot;));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24options.Configuration = &quot;localhost:6379&quot;;
25{
26    &quot;RedisCacheOptions&quot; : {
27        &quot;Configuration&quot;: &quot;localhost:6379&quot;
28    }
29}
30

There is nothing stopping you from building a configuration object to extract the desired settings.

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =&gt;
5{
6    options.Configuration = &quot;localhost:6379&quot;;
7});
8
9builder.Services.AddSwaggerGen(c =&gt;
10{
11    c.SwaggerDoc(&quot;v1&quot;, new() { Title = &quot;BasketAPI&quot;, Version = &quot;v1&quot; });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;BasketAPI v1&quot;));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24options.Configuration = &quot;localhost:6379&quot;;
25{
26    &quot;RedisCacheOptions&quot; : {
27        &quot;Configuration&quot;: &quot;localhost:6379&quot;
28    }
29}
30IConfiguration configuration = new ConfigurationBuilder()
31                            .AddJsonFile(&quot;appsettings.json&quot;)
32                            .Build();
33
34var builder = WebApplication.CreateBuilder(args);
35// Add services to the container.
36builder.Services.AddControllers();
37builder.Services.AddStackExchangeRedisCache(options =&gt; {
38    options.Configuration = configuration[&quot;RedisCacheOptions:Configuration&quot;];
39});
40
41//...
42

Source https://stackoverflow.com/questions/69390676

QUESTION

Android Build Error: &quot;lStar not found...&quot;

Asked 2022-Feb-18 at 06:59

I have error like this after trying to build my apps in Emulator

/Users/joel/.gradle/caches/transforms-3/06231cc1265260b25a06bafce7a4176f/transformed/core-1.7.0-alpha02/res/values/values.xml:105:5-114:25: AAPT: error: resource android:attr/lStar not found.

I don't know what causes this error. After digging some answer which has similarly error (but in flutter) Problem. But still not solved my issue.

I have this dependency in my project

1buildscript {
2    repositories {
3        google()
4        maven { url 'https://plugins.gradle.org/m2/' }
5    }
6
7    dependencies {
8        classpath 'com.google.gms:google-services:4.3.3'
9        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.3.0'
10    }
11}
12apply plugin: 'com.android.application'
13apply plugin: 'com.google.gms.google-services'
14apply plugin: 'kotlin-android'
15apply plugin: 'kotlin-android-extensions'
16apply plugin: 'kotlin-kapt'
17apply plugin: 'com.google.firebase.crashlytics'
18
19repositories {
20    maven { url 'https://maven.fabric.io/public' }
21    maven { url 'https://maven.google.com' }
22    maven { url  &quot;https://teads.jfrog.io/artifactory/SDKAndroid-maven-prod&quot;}
23    mavenCentral()
24
25}
26
27android {
28    compileSdkVersion 29
29    buildToolsVersion '28.0.3'
30    defaultConfig {
31        applicationId &quot;mobile.apps.my&quot;
32        minSdkVersion 17
33        targetSdkVersion 29
34        multiDexEnabled true
35        versionCode 152
36        versionName &quot;8.1.7&quot;
37        vectorDrawables.useSupportLibrary = true // This line hereP
38        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
39    }
40
41    compileOptions {
42        sourceCompatibility JavaVersion.VERSION_1_8
43        targetCompatibility JavaVersion.VERSION_1_8
44    }
45
46    dataBinding {
47        enabled = true
48    }
49
50    buildTypes {
51        debug {
52            firebaseCrashlytics {
53                mappingFileUploadEnabled false
54            }
55        }
56
57        release {
58            minifyEnabled true
59            shrinkResources true
60            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
61        }
62    }
63
64    lintOptions {
65        checkReleaseBuilds false
66        abortOnError false
67    }
68}
69
70dependencies {
71
72    implementation fileTree(include: ['*.jar'], dir: 'libs')
73    androidTestImplementation('androidx.test.espresso:espresso-core:3.2.0-beta01', {
74        exclude group: 'com.android.support', module: 'support-annotations'
75    })
76    //noinspection GradleCompatible
77    implementation 'androidx.appcompat:appcompat:1.4.0-alpha03'
78    implementation &quot;androidx.appcompat:appcompat-resources:1.4.0-alpha03&quot;
79
80    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
81    implementation 'androidx.preference:preference:1.1.1'
82    implementation 'com.google.android.material:material:1.4.0'
83    implementation 'androidx.recyclerview:recyclerview:1.2.1'
84    implementation 'androidx.cardview:cardview:1.0.0'
85    implementation 'androidx.percentlayout:percentlayout:1.0.0'
86
87    implementation 'com.google.android.gms:play-services-analytics:17.0.0'
88    implementation 'it.sephiroth.android.library.imagezoom:imagezoom:2.3.0'
89    testImplementation 'org.json:json:20140107'
90    implementation 'com.comscore:android-analytics:6.1.0'
91    implementation 'com.android.support:customtabs:29.0.0'
92    implementation 'androidx.viewpager2:viewpager2:1.0.0'
93    implementation 'com.android.support:customtabs:29.0.0'
94
95    // Kodein Dependency Injection
96    implementation 'org.kodein.di:kodein-di-generic-jvm:6.2.1'
97    implementation 'org.kodein.di:kodein-di-framework-android-x:6.2.1'
98
99    // RETROFIT
100    implementation 'com.squareup.retrofit2:retrofit:2.6.0'
101    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
102    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
103    implementation 'com.google.code.gson:gson:2.8.5'
104    implementation 'com.squareup.retrofit2:converter-scalars:2.1.0' // for test String
105
106
107    // Room components
108    implementation &quot;androidx.room:room-runtime:2.2.5&quot;
109    kapt &quot;androidx.room:room-compiler:2.2.5&quot;
110    implementation &quot;androidx.room:room-ktx:2.2.5&quot;
111    androidTestImplementation &quot;androidx.room:room-testing:2.2.5&quot;
112
113    // Lifecycle components
114    implementation 'android.arch.lifecycle:extensions:1.1.1'
115    implementation 'androidx.paging:paging-runtime:2.1.2'
116
117    // UI
118    implementation 'com.squareup.picasso:picasso:2.71828'
119    implementation 'com.geniusforapp.fancydialog:FancyDialog:0.1.4'
120    implementation 'com.github.bluzwong:swipeback:0.2.0@aar'
121    implementation 'com.airbnb.android:lottie:3.6.0'
122
123    implementation 'com.veinhorn.scrollgalleryview:library:1.2.6'
124    implementation 'com.veinhorn.scrollgalleryview:picasso-loader:1.2.4'
125    implementation 'com.github.rubensousa:bottomsheetbuilder:1.6.1'
126    implementation &quot;com.andkulikov:transitionseverywhere:1.8.1&quot;
127
128
129    // HTTP LOGGING
130    implementation 'com.jakewharton.timber:timber:4.7.1'
131    implementation 'org.jsoup:jsoup:1.13.1'
132    implementation 'androidx.multidex:multidex:2.0.1'
133
134
135    // ADS
136    implementation 'com.android.support:support-annotations:28.0.0'
137    // Required Dependency by Audience Network SDK
138    implementation 'com.google.android.gms:play-services-ads:19.7.0'
139    implementation 'com.google.android.gms:play-services-basement:17.6.0'
140    implementation(&quot;tv.teads.sdk.android:sdk:4.7.2@aar&quot;) {
141        transitive = true
142    }
143    implementation 'com.criteo.publisher:criteo-publisher-sdk:4.0.0'
144    implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0'
145    implementation 'com.google.android.gms:play-services-base:17.6.0'
146
147    implementation ('com.facebook.android:audience-network-sdk:5.5.0'){
148        exclude group: 'com.google.android.gms'
149    }
150
151    implementation 'com.google.firebase:firebase-crashlytics:17.4.0'
152
153    implementation &quot;androidx.core:core-ktx:1.6.0&quot;  // I have update this based on other solution
154    implementation &quot;androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1&quot;
155    implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot;
156
157    // COROUTINES
158    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1'
159    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
160    implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
161
162    // Kotlin + coroutines
163    implementation &quot;androidx.work:work-runtime-ktx:2.5.0&quot;
164
165    implementation 'com.github.mumayank:AirLocation:1.3.1'
166    androidTestImplementation 'androidx.test:rules:1.3.0-beta01'
167
168    implementation 'com.android.installreferrer:installreferrer:2.2'
169
170    //ANIMATION
171    implementation 'com.daimajia.androidanimations:library:2.4@aar'
172    implementation 'com.infideap.drawerbehavior:drawer-behavior:1.0.4'
173    implementation 'com.romandanylyk:pageindicatorview:1.0.3'
174
175    implementation 'org.ocpsoft.prettytime:prettytime:5.0.0.Final'
176
177    //SOCIAL
178    implementation 'com.google.android.gms:play-services-auth:19.0.0'
179
180}
181

I have tried to upgrade version of androidx.core:core-ktx:1.6.0 then sync or invalidate cache/restart. But none of them give me good result. I am sure yesterday my project was alright with same dependency. Someone please help me, if this question unclear let me add more information. Thanks

ANSWER

Answered 2021-Sep-28 at 17:18

I managed to fix this by upgrading compileSdk to 31 and kotlin gradle plugin to 1.5.10

1buildscript {
2    repositories {
3        google()
4        maven { url 'https://plugins.gradle.org/m2/' }
5    }
6
7    dependencies {
8        classpath 'com.google.gms:google-services:4.3.3'
9        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.3.0'
10    }
11}
12apply plugin: 'com.android.application'
13apply plugin: 'com.google.gms.google-services'
14apply plugin: 'kotlin-android'
15apply plugin: 'kotlin-android-extensions'
16apply plugin: 'kotlin-kapt'
17apply plugin: 'com.google.firebase.crashlytics'
18
19repositories {
20    maven { url 'https://maven.fabric.io/public' }
21    maven { url 'https://maven.google.com' }
22    maven { url  &quot;https://teads.jfrog.io/artifactory/SDKAndroid-maven-prod&quot;}
23    mavenCentral()
24
25}
26
27android {
28    compileSdkVersion 29
29    buildToolsVersion '28.0.3'
30    defaultConfig {
31        applicationId &quot;mobile.apps.my&quot;
32        minSdkVersion 17
33        targetSdkVersion 29
34        multiDexEnabled true
35        versionCode 152
36        versionName &quot;8.1.7&quot;
37        vectorDrawables.useSupportLibrary = true // This line hereP
38        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
39    }
40
41    compileOptions {
42        sourceCompatibility JavaVersion.VERSION_1_8
43        targetCompatibility JavaVersion.VERSION_1_8
44    }
45
46    dataBinding {
47        enabled = true
48    }
49
50    buildTypes {
51        debug {
52            firebaseCrashlytics {
53                mappingFileUploadEnabled false
54            }
55        }
56
57        release {
58            minifyEnabled true
59            shrinkResources true
60            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
61        }
62    }
63
64    lintOptions {
65        checkReleaseBuilds false
66        abortOnError false
67    }
68}
69
70dependencies {
71
72    implementation fileTree(include: ['*.jar'], dir: 'libs')
73    androidTestImplementation('androidx.test.espresso:espresso-core:3.2.0-beta01', {
74        exclude group: 'com.android.support', module: 'support-annotations'
75    })
76    //noinspection GradleCompatible
77    implementation 'androidx.appcompat:appcompat:1.4.0-alpha03'
78    implementation &quot;androidx.appcompat:appcompat-resources:1.4.0-alpha03&quot;
79
80    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
81    implementation 'androidx.preference:preference:1.1.1'
82    implementation 'com.google.android.material:material:1.4.0'
83    implementation 'androidx.recyclerview:recyclerview:1.2.1'
84    implementation 'androidx.cardview:cardview:1.0.0'
85    implementation 'androidx.percentlayout:percentlayout:1.0.0'
86
87    implementation 'com.google.android.gms:play-services-analytics:17.0.0'
88    implementation 'it.sephiroth.android.library.imagezoom:imagezoom:2.3.0'
89    testImplementation 'org.json:json:20140107'
90    implementation 'com.comscore:android-analytics:6.1.0'
91    implementation 'com.android.support:customtabs:29.0.0'
92    implementation 'androidx.viewpager2:viewpager2:1.0.0'
93    implementation 'com.android.support:customtabs:29.0.0'
94
95    // Kodein Dependency Injection
96    implementation 'org.kodein.di:kodein-di-generic-jvm:6.2.1'
97    implementation 'org.kodein.di:kodein-di-framework-android-x:6.2.1'
98
99    // RETROFIT
100    implementation 'com.squareup.retrofit2:retrofit:2.6.0'
101    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
102    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
103    implementation 'com.google.code.gson:gson:2.8.5'
104    implementation 'com.squareup.retrofit2:converter-scalars:2.1.0' // for test String
105
106
107    // Room components
108    implementation &quot;androidx.room:room-runtime:2.2.5&quot;
109    kapt &quot;androidx.room:room-compiler:2.2.5&quot;
110    implementation &quot;androidx.room:room-ktx:2.2.5&quot;
111    androidTestImplementation &quot;androidx.room:room-testing:2.2.5&quot;
112
113    // Lifecycle components
114    implementation 'android.arch.lifecycle:extensions:1.1.1'
115    implementation 'androidx.paging:paging-runtime:2.1.2'
116
117    // UI
118    implementation 'com.squareup.picasso:picasso:2.71828'
119    implementation 'com.geniusforapp.fancydialog:FancyDialog:0.1.4'
120    implementation 'com.github.bluzwong:swipeback:0.2.0@aar'
121    implementation 'com.airbnb.android:lottie:3.6.0'
122
123    implementation 'com.veinhorn.scrollgalleryview:library:1.2.6'
124    implementation 'com.veinhorn.scrollgalleryview:picasso-loader:1.2.4'
125    implementation 'com.github.rubensousa:bottomsheetbuilder:1.6.1'
126    implementation &quot;com.andkulikov:transitionseverywhere:1.8.1&quot;
127
128
129    // HTTP LOGGING
130    implementation 'com.jakewharton.timber:timber:4.7.1'
131    implementation 'org.jsoup:jsoup:1.13.1'
132    implementation 'androidx.multidex:multidex:2.0.1'
133
134
135    // ADS
136    implementation 'com.android.support:support-annotations:28.0.0'
137    // Required Dependency by Audience Network SDK
138    implementation 'com.google.android.gms:play-services-ads:19.7.0'
139    implementation 'com.google.android.gms:play-services-basement:17.6.0'
140    implementation(&quot;tv.teads.sdk.android:sdk:4.7.2@aar&quot;) {
141        transitive = true
142    }
143    implementation 'com.criteo.publisher:criteo-publisher-sdk:4.0.0'
144    implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0'
145    implementation 'com.google.android.gms:play-services-base:17.6.0'
146
147    implementation ('com.facebook.android:audience-network-sdk:5.5.0'){
148        exclude group: 'com.google.android.gms'
149    }
150
151    implementation 'com.google.firebase:firebase-crashlytics:17.4.0'
152
153    implementation &quot;androidx.core:core-ktx:1.6.0&quot;  // I have update this based on other solution
154    implementation &quot;androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1&quot;
155    implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot;
156
157    // COROUTINES
158    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1'
159    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
160    implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
161
162    // Kotlin + coroutines
163    implementation &quot;androidx.work:work-runtime-ktx:2.5.0&quot;
164
165    implementation 'com.github.mumayank:AirLocation:1.3.1'
166    androidTestImplementation 'androidx.test:rules:1.3.0-beta01'
167
168    implementation 'com.android.installreferrer:installreferrer:2.2'
169
170    //ANIMATION
171    implementation 'com.daimajia.androidanimations:library:2.4@aar'
172    implementation 'com.infideap.drawerbehavior:drawer-behavior:1.0.4'
173    implementation 'com.romandanylyk:pageindicatorview:1.0.3'
174
175    implementation 'org.ocpsoft.prettytime:prettytime:5.0.0.Final'
176
177    //SOCIAL
178    implementation 'com.google.android.gms:play-services-auth:19.0.0'
179
180}
181compileSdk = 31
182
183classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10'
184

Source https://stackoverflow.com/questions/69041630

QUESTION

How to register ServiceBusClient for dependency injection?

Asked 2022-Feb-08 at 14:11

I’m trying to register ServiceBusClient from the new Azure.Messaging.ServiceBus package for dependency injection as recommended in this article using ServiceBusClientBuilderExtensions, but I can’t find any documentation or any help online on how exactly to go about this.

I'm trying to add as below

1public override void Configure(IFunctionsHostBuilder builder)
2{
3    ServiceBusClientBuilderExtensions.AddServiceBusClient(builder, Typsy.Domain.Configuration.Settings.Instance().Connections.ServiceBusPrimary);
4}
5

but I'm getting the error

The type 'Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder' must be convertible to 'Azure.Core.Extensions.IAzureClientFactoryBuilder' in order to use it as parameter 'TBuilder' in the generic method 'IAzureClientBuilder<ServiceBusClient,ServiceBusClientOptions> Microsoft.Extensions.Azure.ServiceBusClientBuilderExtensions.AddServiceBusClient(this TBuilder, string)'

enter image description here

If anyone can help with this that'll be great!

ANSWER

Answered 2021-Sep-02 at 20:03

ServiceBusClientBuilderExtensions.AddServiceBusClient is an extension method of IAzureClientFactoryBuilder:

1public override void Configure(IFunctionsHostBuilder builder)
2{
3    ServiceBusClientBuilderExtensions.AddServiceBusClient(builder, Typsy.Domain.Configuration.Settings.Instance().Connections.ServiceBusPrimary);
4}
5public static IAzureClientBuilder&lt;ServiceBusClient, ServiceBusClientOptions&gt; AddServiceBusClient&lt;TBuilder&gt;(this TBuilder builder, string connectionString)
6            where TBuilder : IAzureClientFactoryBuilder
7

To get an instance of IAzureClientFactoryBuilder, you need to call AzureClientServiceCollectionExtensions.AddAzureClients(IServiceCollection, Action<AzureClientFactoryBuilder>) for a given IServiceCollection, which provides a delegate giving an instance of IAzureClientFactoryBuilder. (this method is in the Microsoft.Extensions.Azure NuGet package)

To call that method, you can use the IServiceCollection provided by IFunctionsHostBuilder. With all of that, what you have should look something like:

1public override void Configure(IFunctionsHostBuilder builder)
2{
3    ServiceBusClientBuilderExtensions.AddServiceBusClient(builder, Typsy.Domain.Configuration.Settings.Instance().Connections.ServiceBusPrimary);
4}
5public static IAzureClientBuilder&lt;ServiceBusClient, ServiceBusClientOptions&gt; AddServiceBusClient&lt;TBuilder&gt;(this TBuilder builder, string connectionString)
6            where TBuilder : IAzureClientFactoryBuilder
7public override void Configure(IFunctionsHostBuilder builder)
8{
9    builder.Services.AddAzureClients(clientsBuilder =&gt;
10    {
11        clientsBuilder.AddServiceBusClient(Typsy.Domain.Configuration.Settings.Instance().Connections.ServiceBusPrimary)
12          // (Optional) Provide name for instance to retrieve by with DI
13          .WithName(&quot;Client1Name&quot;)
14          // (Optional) Override ServiceBusClientOptions (e.g. change retry settings)
15          .ConfigureOptions(options =&gt;
16          {
17              options.RetryOptions.Delay = TimeSpan.FromMilliseconds(50);
18              options.RetryOptions.MaxDelay = TimeSpan.FromSeconds(5);
19              options.RetryOptions.MaxRetries = 3;
20          });
21    });
22}
23

To retrieve the named instance, instead of using ServiceBusClient as the injected type you use IAzureClientFactory<ServiceBusClient>. The ServiceBusClient is a Singleton regardless of whether you use a named instance or not.

1public override void Configure(IFunctionsHostBuilder builder)
2{
3    ServiceBusClientBuilderExtensions.AddServiceBusClient(builder, Typsy.Domain.Configuration.Settings.Instance().Connections.ServiceBusPrimary);
4}
5public static IAzureClientBuilder&lt;ServiceBusClient, ServiceBusClientOptions&gt; AddServiceBusClient&lt;TBuilder&gt;(this TBuilder builder, string connectionString)
6            where TBuilder : IAzureClientFactoryBuilder
7public override void Configure(IFunctionsHostBuilder builder)
8{
9    builder.Services.AddAzureClients(clientsBuilder =&gt;
10    {
11        clientsBuilder.AddServiceBusClient(Typsy.Domain.Configuration.Settings.Instance().Connections.ServiceBusPrimary)
12          // (Optional) Provide name for instance to retrieve by with DI
13          .WithName(&quot;Client1Name&quot;)
14          // (Optional) Override ServiceBusClientOptions (e.g. change retry settings)
15          .ConfigureOptions(options =&gt;
16          {
17              options.RetryOptions.Delay = TimeSpan.FromMilliseconds(50);
18              options.RetryOptions.MaxDelay = TimeSpan.FromSeconds(5);
19              options.RetryOptions.MaxRetries = 3;
20          });
21    });
22}
23 public Constructor(IAzureClientFactory&lt;ServiceBusClient&gt; serviceBusClientFactory)
24 {
25     // Wherever you need the ServiceBusClient
26     ServiceBusClient singletonClient1 = serviceBusClientFactory.CreateClient(&quot;Client1Name&quot;)
27 }
28

Source https://stackoverflow.com/questions/68688838

QUESTION

How to create beans dynamically using a DI framework

Asked 2022-Jan-22 at 11:44

requirement is like this: user input is single character followed by an array of integers, such as 'A 1 2', 'B 3 4 5', 'C 1', etc. The single character means which class to construct and integers are input parameter to that constructor. Please note different classes might need different number of integers.

Then we need to write a program to parse user input and create objects accordingly.

My approach was to use regular expression for parsing and hard code which class to call.

But another senior developer said a better idea would be using dependency injection to automatically create objects based on user input. He gave another hint to create an interface and use spring framework dependency injection (not spring boot).

I am still confused how to create beans dynamically in this way. Can anybody help please?

ANSWER

Answered 2022-Jan-22 at 11:44

You can create a common interface for the classes that can be created, and a Factory bean that transforms the input.

1// common interface
2interface MyObject {
3  void someMethod();
4}
5class A implements MyObject {
6  public A(List&lt;Integer&gt; params) { ... }
7}
8class B implements MyObject {
9  public B(List&lt;Integer&gt; params) { ... }
10}
11
12// parsed data
13class Input {
14 char character;
15 List&lt;Integer&gt; ints;
16 // getters, setters
17}
18interface MyObjectFactory {
19  public MyObject apply(Input input);
20}
21
22@Bean
23class MyObjectFactory implements MyObjectFactory {
24  public MyObject apply(Input input) {
25    // create object from input, eg switch over input.getCharacter()
26  };
27}
28// injected
29class MyClientService {
30 @Autowired
31 MyObjectFactory objectFactory;
32
33 public void doStuff() {
34   List&lt;Input&gt; parsedInputs = parse(something);
35   for (Input input : parsedInputs) {
36     MyObject object = objectFactory.apply(input);
37     // ...
38   }
39 }
40}
41

Source https://stackoverflow.com/questions/70794625

QUESTION

What is the difference between static class and singleton in .net mvc project?

Asked 2022-Jan-16 at 10:42

I understand difference between static class and singleton, importantly that singleton can be instantiated once where as static class doesn't need an instance.

This question is with the perspective of a .net mvc project, to help me make decision between using either of them.

So assuming I have Class(es) with methods like the examples given below:

  1. I have a method like ConvertMeterToMiles(int mtr), where there is no dependency injected.

  2. Or a method like SendEmail(str eaddress), where there is no dependency injected but it instantiates new SMTPClient... followed by disposing the SMTPClient in the finally

Assuming I want to put the method into utility service class, then should I create a static class or singleton (ofcource with dependency injection)?

I understand there is no point of scoped or transient because there is no benefit to have new instances.

ANSWER

Answered 2022-Jan-05 at 15:21

Adding a singleton via dependency injection instantiates an instance of the requested class. A static class cannot be instantiated, and so you simply access its methods from elsewhere, based on the static class's access modifiers.

Source https://stackoverflow.com/questions/70594603

QUESTION

.NET Core Dependency Injection how to handle multiple objects

Asked 2021-Dec-29 at 06:56

As the title says I have a .NET Core application that I am trying to convert over to and take advantage of the built in Microsoft Dependency Injection.

I have an object and a base class for the object, call it CommunicationBase and Communicator. When my app starts up and reads the configuration file, I can have N number of objects to instantiate.

Previously, before switching to Dependency Injection, somewhere in my startup routine, where I read the configuration file, I would have a List<CommunicationBase> variable that I would instantiate and add Communicator objects to and at the same time, set some of the base properties, which changed based on how many were in my configuration and each ones properties in config.

How would I achieve this with DI?

I understand that in my services, I would register the type so it can be injected into other class constructors.

For example, services.AddTransient<CommunicationBase, Communicator>(); but as I understand it, this just registers the types with DI. I can inject it into a class and have a random instance of one of them.

How would I then have N number of instances and be able to set properties of each one as I create the instance?

Or, is this a scenario where DI is not necessary or won't work and I need to just do it the way I was doing it before?

Thanks!

ANSWER

Answered 2021-Dec-28 at 11:26

Firstly do you need to has clear the differences between Transient, Scoped, Singleton lifetime. To understand how works with the list of Communicator objects that will be read from your configuration file.

One approuch to resolve your question is

  1. Create an interface ICommunicatorList with one method to get a List, i mean you can envolve the list of communicators.
  2. Create a clase that inherits from ICommunicatorList (for example called CommunicatorList), with a private field for your list of Communicators. On the constructor method set your private field with the list of communicator, o here you can receive like a parameter from the section of the config file to iterate and full your private field.
  3. on this class implement your code to return the list of communicators.
  4. Now, in your startups file you can now create the service services.AddTransient< ICommunicatorList>(x => new CommunicatorList(parameters));

Source https://stackoverflow.com/questions/70505381

QUESTION

Does using Spring boot with javafx will consume a lot of memory?

Asked 2021-Dec-24 at 07:25

I'm willing to use Spring boot technology in my JavaFX application (to get the advantage of its dependency injection), but I'm wondering about the consequences on the memory, as you know any class with a "component" notation will be loaded to the MetaSpace (since it Spring boot will create a static object from it), so with tens of JavaFx view controllers loaded to the MetaSpace they will never get garbage collected from the launching of the application to the end, which is obviously a bad thing, is there any way to get around of this issue?

ANSWER

Answered 2021-Dec-24 at 07:25

You write in comments:

JavaFX applications when the view controller doesn't get garbage collected means also the view objects will always stay there TableViews,ListViews,Panes ... which may take some important space

But I don’t think it needs to be that way.

The controller instance which references the Java nodes is just a Java object like any other and will be available for garbage collection when there are no more references to it in the JVM.

Let’s say you configure your JavaFX SpringBoot integration like this:

So you configure your controller factory to use Spring beans:

1fxmlLoader.setControllerFactory(
2    springContext::getBean
3);
4

Then your controllers are Spring beans whose scope you can control.

If you use prototype scope:

1fxmlLoader.setControllerFactory(
2    springContext::getBean
3);
4@Bean
5@Scope(&quot;prototype&quot;)
6public PersonController personControllerPrototype() {
7    return new PersonController();
8}
9

Then the behavior is as specified in:

Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance.

Typically you will create a controller and add a reference to the object tree that it instantiates into the scene graph. If you replace the tree in the scene graph when you navigate, and you don’t keep a reference to the controller anywhere, then the controller and any other associated nodes which have been removed from the scene graph can be garbage collected.

Or, if you wanted to just load the fxml once and keep the controller around forever you could use singleton scope to do that.

So basically, you can choose the scope and lifecycle of your controllers to be as best fits your application or the individual controllers that you are using.

Source https://stackoverflow.com/questions/70469497

QUESTION

.Net 6 Console app: WebApplication.CreateBuilder vs Host.CreateDefaultBuilder

Asked 2021-Dec-14 at 08:36

I'm looking into .NET 6, and wanted to build a simple console application, with some dependency injection.

From what i can read, a lot has been done to make the startup (now just program) file, more readable. What does confuse me a bit is, that all improvements seems to have been made to WebApplication.CreateBuilderpart used in API projects, and not the Host.CreateDefaultBuilder. As mentioned in this blog

Microsofts own docs, also only seems to mention WebApplication.

To me it seems like WebApplication is only for web projects, like an API, and i can't find anything that confirms og debunks that.

Is it okay to use WebApplication in a console application, or should i rely on Host, and keep the stacked lambda expressions ?

ANSWER

Answered 2021-Dec-14 at 08:36

WebApplication.CreateBuilderpart() is only used for web/api applications like the name implies Host.CreateDefaultBuilder() is used to build a generic host (without web services, middleware etc) which you can use to build anything other than webhost.

See for example; https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host Which has not changed.

Its true that it feels a bit awkward to build console apps and/or backgroundservices at the moment.

Source https://stackoverflow.com/questions/70344866

QUESTION

Android Instrumented tests with KodeIn

Asked 2021-Nov-30 at 16:26

We have an Android app that is using compose for the view layer and we are using Kodein for all of our dependency injections.

I have a BaseApplication class which is DIAware:

1class BaseApplication : Application(), DIAware {
2    override val di: DI = DI.lazy {
3        import(modules) // modules defined in respective packages
4    }
5}
6

I also have a MainActivity and a nav graph to manage navigation between the various composables.

Problem: How can I properly override these modules in my instrumented tests for MainActivity?

1class BaseApplication : Application(), DIAware {
2    override val di: DI = DI.lazy {
3        import(modules) // modules defined in respective packages
4    }
5}
6@RunWith(AndroidJUnit4::class)
7class MainActivityTest {
8    @get:Rule
9    val composeTestRule = createAndroidComposeRule&lt;MainActivity&gt;()
10
11    val moduleOverrides = DI.Module(allowSilentOverride = true) {
12        // add bindings for fakes w/ allowOverride = true
13    }
14    
15    @Before
16    fun setup() {
17        val application =
18            ApplicationProvider.getApplicationContext() as BaseApplication
19
20        // how can I override the BaseApplication modules for my test?
21    }
22
23}
24

I cant seem to find any clear language on the matter and feel like I am missing something very obvious. Any help would be very much appreciated.

ANSWER

Answered 2021-Nov-30 at 16:26

There are several ways to achieve that. The general approach is to override the actual modules like

1class BaseApplication : Application(), DIAware {
2    override val di: DI = DI.lazy {
3        import(modules) // modules defined in respective packages
4    }
5}
6@RunWith(AndroidJUnit4::class)
7class MainActivityTest {
8    @get:Rule
9    val composeTestRule = createAndroidComposeRule&lt;MainActivity&gt;()
10
11    val moduleOverrides = DI.Module(allowSilentOverride = true) {
12        // add bindings for fakes w/ allowOverride = true
13    }
14    
15    @Before
16    fun setup() {
17        val application =
18            ApplicationProvider.getApplicationContext() as BaseApplication
19
20        // how can I override the BaseApplication modules for my test?
21    }
22
23}
24val someParrentKodeinModule...
25
26val mockModule = Kodein {
27    extend(someParrentKodeinModule, allowOverride = true)
28    bind&lt;Foo&gt;(overrides = true) with provider { Foo2() }
29}
30
31or 
32
33val kodein = Kodein {
34    /* ... */
35    import(testsModule, allowOverride = true)
36}
37

where testsModule is some module that already defines all the needed mock components that will be overridden in the main one. Your approach is also good. The key point is to replace your DI with the needed one - this can be done making the DI in your app - var instead of val and assigning new value to it. But you will have to drop DIAware

1class BaseApplication : Application(), DIAware {
2    override val di: DI = DI.lazy {
3        import(modules) // modules defined in respective packages
4    }
5}
6@RunWith(AndroidJUnit4::class)
7class MainActivityTest {
8    @get:Rule
9    val composeTestRule = createAndroidComposeRule&lt;MainActivity&gt;()
10
11    val moduleOverrides = DI.Module(allowSilentOverride = true) {
12        // add bindings for fakes w/ allowOverride = true
13    }
14    
15    @Before
16    fun setup() {
17        val application =
18            ApplicationProvider.getApplicationContext() as BaseApplication
19
20        // how can I override the BaseApplication modules for my test?
21    }
22
23}
24val someParrentKodeinModule...
25
26val mockModule = Kodein {
27    extend(someParrentKodeinModule, allowOverride = true)
28    bind&lt;Foo&gt;(overrides = true) with provider { Foo2() }
29}
30
31or 
32
33val kodein = Kodein {
34    /* ... */
35    import(testsModule, allowOverride = true)
36}
37class BaseApplication : Application() {
38    var di: DI = DI.lazy {
39        import(modules) // modules defined in respective packages
40    }
41}
42
43@Before
44    fun setup() {
45        val application =
46            ApplicationProvider.getApplicationContext() as BaseApplication
47
48       application.di = moduleOverrides
49    }
50
51

Something like that.

And generally using single DI for the app inside the App class is not recommended. Use specialized modules for each component of the app you want to test

Source https://stackoverflow.com/questions/70101438

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Dependency Injection

Tutorials and Learning Resources are not available at this moment for Dependency Injection

Share this Page

share link

Get latest updates on Dependency Injection