├── .editorconfig ├── .gitattributes ├── .gitignore ├── README.md ├── SqliteConsole.Core ├── Entities │ └── Example.cs └── SqliteConsole.Core.csproj ├── SqliteConsole.Infrastructure ├── Data │ └── SqliteConsoleContext.cs ├── Services │ ├── ExampleService.cs │ └── IExampeService.cs └── SqliteConsole.Infrastructure.csproj ├── SqliteConsole.sln └── SqliteConsole ├── Program.cs ├── SqliteConsole.csproj └── appsettings.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # Remove the line below if you want to inherit .editorconfig settings from higher directories 2 | root = true 3 | 4 | # C# files 5 | [*.cs] 6 | 7 | #### Core EditorConfig Options #### 8 | 9 | # Indentation and spacing 10 | indent_size = 4 11 | indent_style = space 12 | tab_width = 4 13 | 14 | # New line preferences 15 | end_of_line = crlf 16 | insert_final_newline = false 17 | 18 | #### .NET Coding Conventions #### 19 | 20 | # Organize usings 21 | dotnet_separate_import_directive_groups = false 22 | dotnet_sort_system_directives_first = false 23 | file_header_template = unset 24 | 25 | # this. and Me. preferences 26 | dotnet_style_qualification_for_event = false:silent 27 | dotnet_style_qualification_for_field = false:silent 28 | dotnet_style_qualification_for_method = false:silent 29 | dotnet_style_qualification_for_property = false:silent 30 | 31 | # Language keywords vs BCL types preferences 32 | dotnet_style_predefined_type_for_locals_parameters_members = true:silent 33 | dotnet_style_predefined_type_for_member_access = true:silent 34 | 35 | # Parentheses preferences 36 | dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent 37 | dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent 38 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent 39 | dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent 40 | 41 | # Modifier preferences 42 | dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent 43 | 44 | # Expression-level preferences 45 | dotnet_style_coalesce_expression = true:suggestion 46 | dotnet_style_collection_initializer = true:suggestion 47 | dotnet_style_explicit_tuple_names = true:suggestion 48 | dotnet_style_null_propagation = true:suggestion 49 | dotnet_style_object_initializer = true:suggestion 50 | dotnet_style_operator_placement_when_wrapping = beginning_of_line 51 | dotnet_style_prefer_auto_properties = true:silent 52 | dotnet_style_prefer_compound_assignment = true:suggestion 53 | dotnet_style_prefer_conditional_expression_over_assignment = true:silent 54 | dotnet_style_prefer_conditional_expression_over_return = true:silent 55 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion 56 | dotnet_style_prefer_inferred_tuple_names = true:suggestion 57 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion 58 | dotnet_style_prefer_simplified_boolean_expressions = true:suggestion 59 | dotnet_style_prefer_simplified_interpolation = true:suggestion 60 | 61 | # Field preferences 62 | dotnet_style_readonly_field = true:suggestion 63 | 64 | # Parameter preferences 65 | dotnet_code_quality_unused_parameters = all:suggestion 66 | 67 | # Suppression preferences 68 | dotnet_remove_unnecessary_suppression_exclusions = none 69 | 70 | #### C# Coding Conventions #### 71 | 72 | # var preferences 73 | csharp_style_var_elsewhere = false:silent 74 | csharp_style_var_for_built_in_types = false:silent 75 | csharp_style_var_when_type_is_apparent = false:silent 76 | 77 | # Expression-bodied members 78 | csharp_style_expression_bodied_accessors = true:silent 79 | csharp_style_expression_bodied_constructors = false:silent 80 | csharp_style_expression_bodied_indexers = true:silent 81 | csharp_style_expression_bodied_lambdas = true:silent 82 | csharp_style_expression_bodied_local_functions = false:silent 83 | csharp_style_expression_bodied_methods = false:silent 84 | csharp_style_expression_bodied_operators = false:silent 85 | csharp_style_expression_bodied_properties = true:silent 86 | 87 | # Pattern matching preferences 88 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion 89 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion 90 | csharp_style_prefer_not_pattern = true:suggestion 91 | csharp_style_prefer_pattern_matching = true:silent 92 | csharp_style_prefer_switch_expression = true:suggestion 93 | 94 | # Null-checking preferences 95 | csharp_style_conditional_delegate_call = true:suggestion 96 | 97 | # Modifier preferences 98 | csharp_prefer_static_local_function = true:suggestion 99 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent 100 | 101 | # Code-block preferences 102 | csharp_prefer_braces = true:silent 103 | csharp_prefer_simple_using_statement = true:suggestion 104 | 105 | # Expression-level preferences 106 | csharp_prefer_simple_default_expression = true:suggestion 107 | csharp_style_deconstructed_variable_declaration = true:suggestion 108 | csharp_style_inlined_variable_declaration = true:suggestion 109 | csharp_style_pattern_local_over_anonymous_function = true:suggestion 110 | csharp_style_prefer_index_operator = true:suggestion 111 | csharp_style_prefer_range_operator = true:suggestion 112 | csharp_style_throw_expression = true:suggestion 113 | csharp_style_unused_value_assignment_preference = discard_variable:suggestion 114 | csharp_style_unused_value_expression_statement_preference = discard_variable:silent 115 | 116 | # 'using' directive preferences 117 | csharp_using_directive_placement = inside_namespace:silent 118 | 119 | #### C# Formatting Rules #### 120 | 121 | # New line preferences 122 | csharp_new_line_before_catch = true 123 | csharp_new_line_before_else = true 124 | csharp_new_line_before_finally = true 125 | csharp_new_line_before_members_in_anonymous_types = true 126 | csharp_new_line_before_members_in_object_initializers = true 127 | csharp_new_line_before_open_brace = all 128 | csharp_new_line_between_query_expression_clauses = true 129 | 130 | # Indentation preferences 131 | csharp_indent_block_contents = true 132 | csharp_indent_braces = false 133 | csharp_indent_case_contents = true 134 | csharp_indent_case_contents_when_block = true 135 | csharp_indent_labels = one_less_than_current 136 | csharp_indent_switch_labels = true 137 | 138 | # Space preferences 139 | csharp_space_after_cast = false 140 | csharp_space_after_colon_in_inheritance_clause = true 141 | csharp_space_after_comma = true 142 | csharp_space_after_dot = false 143 | csharp_space_after_keywords_in_control_flow_statements = true 144 | csharp_space_after_semicolon_in_for_statement = true 145 | csharp_space_around_binary_operators = before_and_after 146 | csharp_space_around_declaration_statements = false 147 | csharp_space_before_colon_in_inheritance_clause = true 148 | csharp_space_before_comma = false 149 | csharp_space_before_dot = false 150 | csharp_space_before_open_square_brackets = false 151 | csharp_space_before_semicolon_in_for_statement = false 152 | csharp_space_between_empty_square_brackets = false 153 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 154 | csharp_space_between_method_call_name_and_opening_parenthesis = false 155 | csharp_space_between_method_call_parameter_list_parentheses = false 156 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 157 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 158 | csharp_space_between_method_declaration_parameter_list_parentheses = false 159 | csharp_space_between_parentheses = false 160 | csharp_space_between_square_brackets = false 161 | 162 | # Wrapping preferences 163 | csharp_preserve_single_line_blocks = true 164 | csharp_preserve_single_line_statements = true 165 | 166 | #### Naming styles #### 167 | 168 | # Naming rules 169 | 170 | dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion 171 | dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface 172 | dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i 173 | 174 | dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion 175 | dotnet_naming_rule.types_should_be_pascal_case.symbols = types 176 | dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case 177 | 178 | dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion 179 | dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members 180 | dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case 181 | 182 | # Symbol specifications 183 | 184 | dotnet_naming_symbols.interface.applicable_kinds = interface 185 | dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 186 | dotnet_naming_symbols.interface.required_modifiers = 187 | 188 | dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum 189 | dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 190 | dotnet_naming_symbols.types.required_modifiers = 191 | 192 | dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method 193 | dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 194 | dotnet_naming_symbols.non_field_members.required_modifiers = 195 | 196 | # Naming styles 197 | 198 | dotnet_naming_style.pascal_case.required_prefix = 199 | dotnet_naming_style.pascal_case.required_suffix = 200 | dotnet_naming_style.pascal_case.word_separator = 201 | dotnet_naming_style.pascal_case.capitalization = pascal_case 202 | 203 | dotnet_naming_style.begins_with_i.required_prefix = I 204 | dotnet_naming_style.begins_with_i.required_suffix = 205 | dotnet_naming_style.begins_with_i.word_separator = 206 | dotnet_naming_style.begins_with_i.capitalization = pascal_case 207 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SQLite .NET 8 Console App 2 | .NET 8.0 Console Application using SQLite with Entity Framework and Dependency Injection 3 | 4 | This example shows how to incorporate ASP.NET concepts such as dependency injection within a console application using [VS Code](https://code.visualstudio.com/) on macOS or linux targets. 5 | 6 | ![vscode](https://user-images.githubusercontent.com/1213591/106406012-9d305c00-63fd-11eb-98e0-c2a0fca08afe.png) 7 | 8 | ## Project Structure 9 | 10 | This solution is divided into three projects: 11 | 12 | - **SqliteConsole**: The main console application 13 | - **SqliteConsole.Core**: Entity models 14 | - **SqliteConsole.Infrasture**: Entity framework database context and service classes 15 | 16 | ## Concepts 17 | 18 | The following concepts are demonstrated within this example console application project: 19 | - SQLite Entity Framework 20 | - Dependency Injection 21 | 22 | ### SQLite Entity Framework 23 | 24 | Using dependency injection, the database context can be passed to a constructor of a class: 25 | 26 | ```cs 27 | public class ExampleService : IExampleService 28 | { 29 | private readonly SqliteConsoleContext context; 30 | 31 | public ExampleService(SqliteConsoleContext sqliteConsoleContext) 32 | { 33 | context = sqliteConsoleContext; 34 | } 35 | ``` 36 | 37 | This way, the context may be used as follows: 38 | 39 | ```cs 40 | public void GetExamples() 41 | { 42 | var examples = context.Examples 43 | .OrderBy(e => e.Name) 44 | .ToList(); 45 | ``` 46 | 47 | Otherwise, there's a factory method to instantiate new contexts: 48 | 49 | ```cs 50 | using (var context = SqliteConsoleContextFactory.Create(config.GetConnectionString("DefaultConnection"))) 51 | { 52 | var examples = context.Examples 53 | .OrderBy(e => e.Name) 54 | .ToList(); 55 | } 56 | ``` 57 | 58 | ### Dependency Injection 59 | 60 | Service classes are added to the main console application's Program.cs: 61 | 62 | ```cs 63 | // Services 64 | var services = new ServiceCollection() 65 | .AddSingleton() 66 | .BuildServiceProvider(); 67 | ``` 68 | 69 | Then, obtain the instance of the service as: 70 | 71 | ```cs 72 | var service = services.GetService(); 73 | ``` 74 | -------------------------------------------------------------------------------- /SqliteConsole.Core/Entities/Example.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace SqliteConsole.Core.Entities 8 | { 9 | public class Example 10 | { 11 | public int Id { get; set; } 12 | public string? Name { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /SqliteConsole.Core/SqliteConsole.Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net8.0 4 | enable 5 | enable 6 | 7 | -------------------------------------------------------------------------------- /SqliteConsole.Infrastructure/Data/SqliteConsoleContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using SqliteConsole.Core.Entities; 3 | 4 | namespace SqliteConsole.Infrastructure.Data 5 | { 6 | 7 | /// 8 | /// Entity framework context 9 | /// 10 | public class SqliteConsoleContext : DbContext 11 | { 12 | public SqliteConsoleContext(DbContextOptions options) 13 | : base(options) 14 | { } 15 | 16 | public DbSet Examples { get; set; } 17 | 18 | protected override void OnModelCreating(ModelBuilder builder) 19 | { 20 | base.OnModelCreating(builder); 21 | 22 | builder.Entity() 23 | .Property(e => e.Name) 24 | .HasColumnType("varchar(512)"); 25 | } 26 | } 27 | 28 | public static class SqliteConsoleContextFactory 29 | { 30 | public static SqliteConsoleContext Create(string connectionString) 31 | { 32 | var optionsBuilder = new DbContextOptionsBuilder(); 33 | optionsBuilder.UseSqlite(connectionString); 34 | 35 | var context = new SqliteConsoleContext(optionsBuilder.Options); 36 | context.Database.EnsureCreated(); 37 | 38 | return context; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /SqliteConsole.Infrastructure/Services/ExampleService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Linq; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.Logging; 7 | using SqliteConsole.Core.Entities; 8 | using SqliteConsole.Infrastructure.Data; 9 | 10 | namespace SqliteConsole.Infrastructure.Services 11 | { 12 | public class ExampleService : IExampleService 13 | { 14 | private readonly IConfigurationRoot config; 15 | private readonly ILogger logger; 16 | private readonly SqliteConsoleContext context; 17 | 18 | public ExampleService(ILoggerFactory loggerFactory, IConfigurationRoot configurationRoot, SqliteConsoleContext sqliteConsoleContext) 19 | { 20 | logger = loggerFactory.CreateLogger(); 21 | config = configurationRoot; 22 | context = sqliteConsoleContext; 23 | } 24 | 25 | public void GetExamples() 26 | { 27 | logger.LogInformation($"All examples from database: {config["ConnectionStrings:DefaultConnection"]}"); 28 | 29 | var examples = context.Examples 30 | .OrderBy(e => e.Name) 31 | .ToList(); 32 | 33 | foreach (var example in examples) 34 | { 35 | logger.LogInformation($"Name: {example.Name}"); 36 | } 37 | } 38 | 39 | public void AddExample(string name) 40 | { 41 | logger.LogInformation($"Adding example: {name}"); 42 | 43 | var example = new Example() 44 | { 45 | Name = name 46 | }; 47 | 48 | context.Examples.Add(example); 49 | context.SaveChanges(); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /SqliteConsole.Infrastructure/Services/IExampeService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace SqliteConsole.Infrastructure.Services 6 | { 7 | public interface IExampleService 8 | { 9 | 10 | void GetExamples(); 11 | void AddExample(string name); 12 | 13 | } 14 | } -------------------------------------------------------------------------------- /SqliteConsole.Infrastructure/SqliteConsole.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net8.0 4 | enable 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /SqliteConsole.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33205.214 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqliteConsole", "SqliteConsole\SqliteConsole.csproj", "{E9E40020-23EB-4113-9EFC-01F7CDA383BE}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqliteConsole.Core", "SqliteConsole.Core\SqliteConsole.Core.csproj", "{2CEE3505-40EF-4785-AA59-72D9D0042CBE}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqliteConsole.Infrastructure", "SqliteConsole.Infrastructure\SqliteConsole.Infrastructure.csproj", "{716B14C2-A633-46A1-972E-7D740B4D3829}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {E9E40020-23EB-4113-9EFC-01F7CDA383BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {E9E40020-23EB-4113-9EFC-01F7CDA383BE}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {E9E40020-23EB-4113-9EFC-01F7CDA383BE}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {E9E40020-23EB-4113-9EFC-01F7CDA383BE}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {2CEE3505-40EF-4785-AA59-72D9D0042CBE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {2CEE3505-40EF-4785-AA59-72D9D0042CBE}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {2CEE3505-40EF-4785-AA59-72D9D0042CBE}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {2CEE3505-40EF-4785-AA59-72D9D0042CBE}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {716B14C2-A633-46A1-972E-7D740B4D3829}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {716B14C2-A633-46A1-972E-7D740B4D3829}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {716B14C2-A633-46A1-972E-7D740B4D3829}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {716B14C2-A633-46A1-972E-7D740B4D3829}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {5EF5C2EB-764F-46CA-9AA0-55C22222338E} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /SqliteConsole/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Logging; 5 | using SqliteConsole.Infrastructure.Data; 6 | using SqliteConsole.Infrastructure.Services; 7 | 8 | // Configuration 9 | var builder = new ConfigurationBuilder() 10 | .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); 11 | var configuration = builder.Build(); 12 | 13 | // Database 14 | var optionsBuilder = new DbContextOptionsBuilder() 15 | .UseSqlite(configuration.GetConnectionString("DefaultConnection")); 16 | var context = new SqliteConsoleContext(optionsBuilder.Options); 17 | context.Database.EnsureCreated(); 18 | 19 | // Services 20 | var services = new ServiceCollection() 21 | .AddLogging(loggingBuilder => 22 | { 23 | loggingBuilder.AddConsole(); 24 | }) 25 | .AddSingleton(configuration) 26 | .AddSingleton(optionsBuilder.Options) 27 | .AddSingleton() 28 | .AddDbContextPool(options => options.UseSqlite(configuration.GetConnectionString("DefaultConnection"))) 29 | .BuildServiceProvider(); 30 | 31 | var logger = (services.GetService() ?? throw new InvalidOperationException()) 32 | .CreateLogger(); 33 | 34 | logger.LogInformation($"Starting application at: {DateTime.Now}"); 35 | 36 | // Example Service 37 | var service = services.GetService(); 38 | service?.AddExample("Test A"); 39 | service?.AddExample("Test B"); 40 | service?.AddExample("Test C"); 41 | service?.GetExamples(); -------------------------------------------------------------------------------- /SqliteConsole/SqliteConsole.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | PreserveNewest 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /SqliteConsole/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Data Source=sqlite.db;" 4 | } 5 | } 6 | --------------------------------------------------------------------------------